I am using MvvmLight and have implemented communication between some of my ViewModels using the MessengerInstance.Send(...) method. It works great!

Recently, though, I have moved from using Synchronous methods to async methods to retrieve data and it looks like this breaks messaging (probably because it executes on a different thread). For example:

public ICommand SomeCommand { get { return new RelayCommand(DoSomething); } }

private async void DoSomething(object obj)
{
    //Used to be SomeWcfService.DoSomething(); with some logic afterward
    await SomeWcfService.DoSomethingAsync().ContinueWith(task => { //Some logic after method completes });

    MessengerInstance.Send(SomeDataToSend, MessageIdentifer.DoSomething);
}
有帮助吗?

解决方案

Instead of using a continuation, just put it after the await:

private async void DoSomething(object obj)
{
    //Used to be SomeWcfService.DoSomething(); with some logic afterward
    var result = await SomeWcfService.DoSomethingAsync();

    // .ContinueWith(task => { //Some logic after method completes });
    // use result here!

    MessengerInstance.Send(SomeDataToSend, MessageIdentifer.DoSomething);
}

If there is no result returned from DoSomethingAsync, you can just leave out the result, and put your code in place.

The continuation, as you wrote it, will not run on the same synchronization context. The await keyword is actually asynchronously waiting your continuation, not the async method from WCF, as well.

If your "some logic" is asynchronous, you can use await within that code, as well.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top