Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Windows.Threading.Dispatcher and WinForms?

Does a System.Windows.Threading.Dispatcher work on the UI-thread of a WinForms application?

If yes, why? It is coming from WindowsBase.dll which seems to be a WPF component.

If not, how can I invoke work units back onto the UI-thread? I've found Control.BeginInvoke(), but it seems clumsy to create a control only to reference the originating thread.

like image 434
David Schmitt Avatar asked Nov 19 '08 19:11

David Schmitt


People also ask

Will WinForms be deprecated?

WinForms won't be deprecated until Win32 is ... which could be quite sometime! WPF on the other hand has few direct dependencies on Win32 so could potentially form the basis of a "fresh start" UI layer on a future version of windows.

Is WinForms multithreaded?

The . NET Framework has full support for running multiple threads at once.

How do I use a dispatcher in WinForms?

You can use Dispatcher even in a WinForms app. If you are sure to be on a UI thread (e.g. in an button. Click handler), Dispatcher. CurrentDispatcher gives you the UI thread dispatcher that you can later use to dispatch from background threads to the UI thread as usual.

What is the relationship between threads and dispatchers?

A Dispatcher is responsible for managing the work for a thread. The UI thread is the thread that renders the UI. The UI thread queues work items inside an object called a Dispatcher. The Dispatcher selects work items on a priority basis and runs each one to completion.


2 Answers

You can use Dispatcher even in a WinForms app.

If you are sure to be on a UI thread (e.g. in an button.Click handler), Dispatcher.CurrentDispatcher gives you the UI thread dispatcher that you can later use to dispatch from background threads to the UI thread as usual.

like image 115
Martin Konicek Avatar answered Sep 18 '22 16:09

Martin Konicek


Dispatcher is a WPF component, not a WinForms component.

If you want to dispatch work items on the UI thread, then you would have to either use Control.BeginInvoke as you've already found, or react to ResetEvents/WaitObjects across threads.

Usually invoking work items on the UI thread is a bad thing unless it's a UI piece of work (ie. updating a control's content or something) in which case the Control.BeginInvoke() would be sufficient.

like image 41
OJ. Avatar answered Sep 17 '22 16:09

OJ.