Is it wrong to use the Dispatcher within my ViewModel?

Although it works, using Dispatcher in my viewmodel like this seems out of place to me.

This isn’t a completely unreasonable approach, and is the approach that many people take. Personally, if you’re using WPF (or Silverlight 5), and have access to the TPL, I prefer to use the TPL to handle this.

Assuming your ViewModel is constructed on the UI thread (ie: by the View, or in response to a View related event), which is the case nearly always IMO, you can add this to your constructor:

// Add to class:
TaskFactory uiFactory;

public MyViewModel()
{
    // Construct a TaskFactory that uses the UI thread's context
    uiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
}

Then, when you get your event, you can use this to marshal it:

void Chat_Incoming(Game.ChatLine line)
{
    uiFactory.StartNew( () => Chat.Add(line) );
}

Note that this is slightly different than your original, since it’s no longer blocking (this is more like using BeginInvoke instead of Invoke). If you need this to block until the UI finishes processing the message, you can use:

void Chat_Incoming(Game.ChatLine line)
{
    uiFactory.StartNew( () => Chat.Add(line) ).Wait();
}

Leave a Comment