10

Quick question - how do I call async methods from within a Prism event aggregator subscriber action? E.g.

_eventAggregator.GetEvent<PubSubEvent<SomeMessage>>()
   .Subscribe((msg) => {
                       DoSomething();
                       await DoSomethingAsync();
                       DoSomethingElse();
                    });
3
  • 3
    You can stick async in front of your lambda e.g. async (msg) => { ... }, but Subscribe won't wait for it to complete. Commented Jun 9, 2016 at 12:13
  • @CharlesMager Aah, as simple as that! Many thanks. Commented Jun 9, 2016 at 12:15
  • @CharlesMager this will create async void which is not recommended solution. Commented Dec 3, 2018 at 14:46

2 Answers 2

3

With current Prism implementation, it is not possible see here.

But I have found an alternate implementation of Prism's EventAggregator, which allows async subscriptions. See here.

This new event async aggregator overloads can be used in the same way as the original one:

Subscription to event is exactly the same with another overload:


    _eventAggregator.GetEvent<<TfsHookEvent<WorkItemUpdatedPayload>>().Subscribe(WorkItem_Updated);

Event handler:


    private async Task WorkItem_Updated(WorkItemUpdatedPayload obj)
    {
        await CheckAsync();
    }
Sign up to request clarification or add additional context in comments.

2 Comments

How do we include those classes? There does not seem to be a Nuget package, and simply pasting the necessary files into my own solution results in conflicting classes
I downloaded Prism sources and replaced files from the source above. Not an ideal solution. There is no NuGet package.
2

Just making @Charles Mager a answer

_eventAggregator.GetEvent<PubSubEvent<SomeMessage>>()
   .Subscribe(async(msg) => {
                       DoSomething();
                       await DoSomethingAsync();
                       DoSomethingElse();
                    });

2 Comments

Will it create async void method from this lambda method ? Isn't it not recommended ?
No, this is no good solution. It works but it is a "fire and forget" style. No exceptions are caught.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.