Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7182267
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T17:44:02+00:00 2026-05-28T17:44:02+00:00

I have a main thread that contains my WPF GUI and one or more

  • 0

I have a main thread that contains my WPF GUI and one or more background threads that occassionally need to execute code in the main thread asynchronously (e.g. a status update in the GUI).

There are two ways (that I know of, maybe more) to accomplish this:

  1. by scheduling a task using the TaskScheduler from the target thread’s synchronization context, and
  2. by invoking a delegate using the Dispatcher from the target thread.

In code:

using System.Threading.Tasks;
using System.Threading;

Action mainAction = () => MessageBox.Show(string.Format("Hello from thread {0}", Thread.CurrentThread.ManagedThreadId));
Action backgroundAction;

// Execute in main thread directly (for verifiying the thread ID)
mainAction();

// Execute in main thread via TaskScheduler
var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
backgroundAction = () => Task.Factory.StartNew(mainAction, CancellationToken.None, TaskCreationOptions.None, taskScheduler);
Task.Factory.StartNew(backgroundAction);

// Execute in main thread via Dispatcher
var dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
backgroundAction = () => dispatcher.BeginInvoke(mainAction);
Task.Factory.StartNew(backgroundAction);

I like the TPL-based version, because I already use TPL a lot and it provides me with a lot of flexibility, e.g. by waiting on the task or chaining it with other tasks. However, in most examples of WPF code I have seen so far, the Dispatcher variant was used.

Assuming I didn’t need any of that flexibility and only wanted to execute some code in the target thread, what are the reasons one would prefer one way over the other? Are there any performance implications?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T17:44:03+00:00Added an answer on May 28, 2026 at 5:44 pm

    I highly recommend that you read the Task-based Asynchronous Pattern document. This will allow you to structure your APIs to be ready when async and await hit the streets.

    I used to use TaskScheduler to queue updates, similar to your solution (blog post), but I no longer recommend that approach.

    The TAP document has a simple solution that solves the problem more elegantly: if a background operation wants to issue progress reports, then it takes an argument of type IProgress<T>:

    public interface IProgress<in T> { void Report(T value); }
    

    It’s then relatively simple to provide a basic implementation:

    public sealed class EventProgress<T> : IProgress<T>
    {
      private readonly SynchronizationContext syncContext;
    
      public EventProgress()
      {
        this.syncContext = SynchronizationContext.Current ?? new SynchronizationContext();
      }
    
      public event Action<T> Progress;
    
      void IProgress<T>.Report(T value)
      {
        this.syncContext.Post(_ =>
        {
          if (this.Progress != null)
            this.Progress(value);
        }, null);
      }
    }
    

    (SynchronizationContext.Current is essentially TaskScheduler.FromCurrentSynchronizationContext without the need for actual Tasks).

    The Async CTP contains IProgress<T> and a Progress<T> type that is similar to the EventProgress<T> above (but more performant). If you don’t want to install CTP-level stuff, then you can just use the types above.

    To summarize, there are really four options:

    1. IProgress<T> – this is the way asynchronous code in the future will be written. It also forces you to separate your background operation logic from your UI/ViewModel update code, which is a Good Thing.
    2. TaskScheduler – not a bad approach; it’s what I used for a long time before switching to IProgress<T>. It doesn’t force the UI/ViewModel update code out of the background operation logic, though.
    3. SynchronizationContext – same advantages and disadvantages to TaskScheduler, via a lesser-known API.
    4. Dispatcher – really can not recommend this! Consider background operations updating a ViewModel – so there’s nothing UI-specific in the progress update code. In this case, using Dispatcher just tied your ViewModel to your UI platform. Nasty.

    P.S. If you do choose to use the Async CTP, then I have a few additional IProgress<T> implementations in my Nito.AsyncEx library, including one (PropertyProgress) that sends the progress reports through INotifyPropertyChanged (after switching back to the UI thread via SynchronizationContext).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application that has two threads. The first one (the main thread)
I have a program that runs in a few threads. The main thread shares
In my sample application, I have basically two threads. The main thread contains a
I have a main thread that invokes a child thread function at different times
I have a windows form on the main thread and another thread that does
I have my main GUI thread, and a second thread running inside it's own
My Goal I would like to have a main processing thread (non GUI), and
I have a win forms application that contains a Web Browser control. I need
I have the main thread from which I start a window using invokeLater .
i have a listoddata and a list of thread in main thread .i am

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.