Click here to Skip to main content
15,894,017 members
Articles / Desktop Programming / WPF

How to get rid of Dispatcher.Invoke

Rate me:
Please Sign up or sign in to vote.
4.82/5 (7 votes)
8 Dec 2013CPOL 24.2K   170   9   1
Using Task to switch context

Introduction

After struggling with switching context between threads using Dispatcher I'm happy to be able to convey the following solution using a Task instead.  

Using the code

I wrap the task in an execute method that takes an Action.  

C#
//
// private method to switch context.
//
private void Execute(Action action)
{
  try
  {
    // Invoke action on UI thread
    var task = Task.Factory.StartNew(() =>
               {
                 if (action != null)
                    action();
               }, CancellationToken.None, TaskCreationOptions.None, taskScheduler);
    if (task.IsFaulted)
      throw new AggregateException(task.Exception);
  }
  catch (Exception e)
  {
    if (Debugger.IsAttached) Debugger.Break();
    // Handle exception here.
  }
} 

To use the method you need to set the task scheduler within the UI thread and the SynchronizationContext must be set. 

C#
// Must be set on the UI thread
taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();  
C#
// Example 
// Invoke event LogonStatusChanged on the UI thread.
private void InvokeLoginStatusChanged(Object sender, EventArgs e)
{
  if (LogonStatusChanged == null) return;
  Execute(() => LogonStatusChanged(this, e));
}  

Points of Interest

Using a Task  to switch context between threads is tricky when it comes to Unit tests. In those cases you can create you own Synchronization context using the following code.

C#
// Creating you own Synchronization context
[TestInitialize]
private void TestSetup()
{
  SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}  


Note that the Synchronization Context is not created right away when you start your application.
If you reference TaskScheduler.FromCurrentSynchronizationContext() in the App.cs constructor it will always be null

In stead move any initialization to OnStartup

C#
protected override void OnStartup(StartupEventArgs e)
{
  // Initialize here
  base.OnStartup(e);
}  

History 

2013-12-6: The initial version.  
2013-12-8: Added an example. 



License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Denmark Denmark
Name: Niel Morgan Thomas
Born: 1970 in Denmark
Education:
Dataengineer from Odense Technical University.
More than 20 years in IT-business.
Current employment:
Cloud architect at University College Lillebaelt

Comments and Discussions

 
Question5 Pin
Assil16-Jan-14 3:13
professionalAssil16-Jan-14 3:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.