Click here to Skip to main content
12,549,320 members (48,273 online)
Click here to Skip to main content
Add your own
alternative version


9 bookmarked

How to get rid of Dispatcher.Invoke

, 8 Dec 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Using Task to switch context


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.  

// private method to switch context.
private void Execute(Action action)
    // Invoke action on UI thread
    var task = Task.Factory.StartNew(() =>
                 if (action != null)
               }, 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. 

// Must be set on the UI thread
taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();  
// 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.

// Creating you own Synchronization context
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

protected override void OnStartup(StartupEventArgs e)
  // Initialize here


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


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


About the Author

Niel M.Thomas
Denmark Denmark
Name: Niel Morgan Thomas
Born: 1970 in Denmark
Dataengineer from Odense Technical University.
More than 20 years in IT-business.
Current employment:
Working with application development in a major Danish company that produce medical equipment.

You may also be interested in...


Comments and Discussions

Question5 Pin
Assil16-Jan-14 3:13
memberAssil16-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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161021.1 | Last Updated 8 Dec 2013
Article Copyright 2013 by Niel M.Thomas
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid