AsynchronousCommand and MessageMediator in combination?

Topics: Questions
Jul 8, 2012 at 11:42 AM
Edited Jul 8, 2012 at 11:46 AM

My view issues an asynchronous command exposed by the viewmodel, where the execution logic starts a slow task from some dataservice. Do you think this is a reasonable approach?

class DataService : ViewModelServiceBase
{        
    public void LongTask(AsynchronousCommand cancellableAsyncCommand)
    {
        var mediator = ServiceLocator.Instance.ResolveType();
            
        for(var i = 0; i < 500; i++)
        {
            if(cancellableAsyncCommand.IsCancelationRequested)
                return;

            mediator.SendMessage("Step " + i, "DataServiceMessage");
            Thread.Sleep(100);                                               
        }

        mediator.SendMessage("Completed", "DataServiceMessage");
    }
}

public class MainWindowViewModel : ViewModelBase
{
    public MainWindowViewModel() : base()
    {
        CancellableAsyncCommand = new AsynchronousCommand(OnAsyncDummyCommand);
    }
    
    public AsynchronousCommand CancellableAsyncCommand { get; set; }        
    private void OnAsyncDummyCommand()
    {
      var ds = new DataService();
      ds.LongTask(CancellableAsyncCommand);
    }
    
    [MessageRecipient(Tag = "DataServiceMessage")]
    private void DataServiceMessageHandler(string obj)
    {
       MyStringPropertyData = obj; //the UI gets updated
    }
}

Jul 8, 2012 at 3:47 PM

I am not sure whether it is a good thing to implement a command on a service. Normally, services are "mvvm unaware" and should be usable by any technology (such as ASP.NET). 

But, the AsyncCommand is actually an implementation equal to a background worker, so maybe it;'s not bad at all. Just let me know what your experiences are in the future with this usage.

Jul 9, 2012 at 10:44 AM

I ended up using a notification service, something like the one illustrated here: http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Sending-notifications-in-WPF-MVVM-applications.aspx

In this way I made my data service MVVM agnostic, like you pointed out, and it seems to me a much more elegant approach.

Jul 9, 2012 at 6:28 PM

Good option, thanks for sharing this information.