c# – Is there any benefit to using Dispatcher in WinForms?

Question:

In WinForms, you can use the WPF-Dispatcher classes to access the UI from different threads.

However, is there any profit in it compared to using the standard Invoke? Are there any fundamental differences between Invoke and Dispatcher?

From the outside, if you look, then when, it seems, the same amount is needed.

Answer:

In terms of their semantics, they are absolutely equivalent. And their application is similar.

WPF:

  if (Dispatcher.CheckAccess())
  {
       //action
  }
  else
  {
       Dispatcher.Invoke( () => /* action */ );
  }

WinForms:

  if (this.InvokeRequired)
      this.Invoke(() => /* action */);
  else
      //action

But of course it's better to use SynchronizationContext all the same. I believe that it will be better for the eyes, especially when working with WPF using MVVM. Yes, you know that some action should take place in some UI thread, but why drag some special calls / libraries / dependencies, especially those that belong to the UI framework, to the VM layer? Better, of course, to use a sync context.

For example, here's a very good article: Stephen Cleary. Parallel Computing – It's All About the SynchronizationContext

Another thing about the difference between WPF and WinForms dispatchers is that the WPF dispatcher has a higher level of abstraction, there are also priorities and various other things that can be useful and give more flexibility.

Scroll to Top
AllEscort