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.
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.
I provided an example of using
System.Windows.Threading.Dispatcher
in Windows Form in my answer to question "Parallel Programming using TPL on WinForms" since the previous answer to your question:is either misleading or confusing or lacks the concrete usage context:
button.Click
handler does not assure to be on UI thread;One can get dispatcher of WinForm UI thread:
in either button click event handler or anywhere else (in form constructor)
And then use it to execute on UI from other threads, see more details on example below in my answer:
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.I had similar problem using Oracle dependency class which runs on its own thread within Winforms,
When OnChange event fired from Oracle Dependency, I wanted to show the changes in DataGridView by simply setting DataSource to eventargs.Details (which is essentially a DataTable), and it throws: System.InvalidOperationException was unhandled by user code Message=Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
StackOverflow user Brian Peiris (bpeiris@gmail.com) ,collegue of mine showed me this way around:
Use background worker thread as it's UI message pump aware, This MSDN Article though mostly about WPF does state that the BWT is UI aware even for windows forms.
Take a look at backgrounder and see if it fits your needs.