2

Hi guys i am switching one of my projects from windowsforms to WPF. So far i used this piece of code to invoke my GUI objects with data from another thread:

this.Invoke(new Action<NewDiagPacketArrivedEventArgs>(DoSomething), e);

How can I do the same thing in WPF? I found a few posts about using a dispatcher, but I could not get it to work. I would like to have a simple solution. If you know any guides on this topic I would appreciate it.

Thanks

DerBenutzer
  • 311
  • 1
  • 5
  • 20
  • Here is a simple example of how using `Dispatcher.BeginInvoke` in WPF. Have a look at it: http://stackoverflow.com/questions/33316791/issue-with-updating-my-ui – Salah Akbari Jan 06 '16 at 09:51

2 Answers2

7

Try this

this.Dispatcher.Invoke(()=>DoStuffOnGUIThread());

DoStuffInGUIThread() is the method that contains the code you want to execute on the UI thread.

Eike S
  • 116
  • 5
  • Is the short variant `this.Dispatcher.Invoke(DoStuffOnGUIThread);` also possible? – IS4 Jan 06 '16 at 10:01
  • In this case yes. But you can't add parameters and lose the advantage of closures. – Eike S Jan 06 '16 at 10:15
  • If many dispatchers are invoked, they can messup UI while main thread is active, so you should add 'DispatcherPriority.ContextIdle' . It updates UI instantly. – Ben sin aspa Jan 07 '16 at 12:30
2

In Winforms, we use Control.Invoke to marshal the code from other thread to GUI thread. In WPF its Dispatcher.Invoke, every Dispatcher object have its own Dispatcher, on thats queue it will be marshaled.

Dispatcher.BeginInvoke(new Action(() =>
 {
     //Your code
 }));