Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvokeRequired in wpf [duplicate]

I used this function in a Windows forms application:

delegate void ParametrizedMethodInvoker5(int arg);  private void log_left_accs(int arg) {     if (InvokeRequired)      {         Invoke(new ParametrizedMethodInvoker5(log_left_accs), arg);         return;     }      label2.Text = arg.ToString(); } 

But in WPF it doesn't work. Why?

like image 288
oehgr Avatar asked Mar 19 '13 16:03

oehgr


2 Answers

In WPF, the Invoke method is on the dispatcher, so you need to call Dispatcher.Invoke instead of Invoke. Also, there is no InvokeRequired property, but the dispatcher has a CheckAccess method (for some reason, it's hidden in intellisense). So your code should be:

delegate void ParametrizedMethodInvoker5(int arg); void log_left_accs(int arg) {     if (!Dispatcher.CheckAccess()) // CheckAccess returns true if you're on the dispatcher thread     {         Dispatcher.Invoke(new ParametrizedMethodInvoker5(log_left_accs), arg);         return;     }     label2.Text= arg.ToString(); } 
like image 118
Thomas Levesque Avatar answered Sep 26 '22 10:09

Thomas Levesque


In WPF use the CheckAccess method instead of InvokeRequired

if (!CheckAccess()) {    // On a different thread   Dispatcher.Invoke(() => log_left_accs(arg));   return; } 
like image 30
JaredPar Avatar answered Sep 22 '22 10:09

JaredPar