34

我在一个应用程序中使用了这个函数Windows forms

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();
}

但在WPF它不起作用。为什么?

4

4 回答 4

67

在 WPF 中,该Invoke方法在调度程序上,因此您需要调用Dispatcher.Invoke而不是Invoke. 此外,没有InvokeRequired属性,但调度程序有一个CheckAccess方法(出于某种原因,它隐藏在智能感知中)。所以你的代码应该是:

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();
}
于 2013-03-19T16:21:13.657 回答
21

在 WPF 中使用CheckAccess方法而不是InvokeRequired

if (!CheckAccess()) { 
  // On a different thread
  Dispatcher.Invoke(() => log_left_accs(arg));
  return;
}
于 2013-03-19T16:19:50.123 回答
0

check Dispatcher.CheckAccess()

于 2013-03-19T16:19:23.563 回答
-1

WPF 使用Dispatcher来控制对消息泵的访问,而不是让每个控件负责访问 UI 线程。

您应该使用Dispatcher.Invoke将委托添加到 WPF 应用程序中的 UI 线程。

It's also worth noting that InvokeRequired is not really needed in a winform app, nor is it something that you should be checking for in a WPF application. You should know that you're not in the UI thread when you call Invoke. You shouldn't ever be in a situation where a given method is sometimes called from the UI thread and sometimes called from a background thread. Choose one; either always force the caller to invoke to the UI thread before calling a given method (so you don't need to invoke) or assume that the caller won't be in the UI thread when the method is called. It's also worth noting that calling Invoke when you're already in the UI thread is just fine. There are no errors or problems that will result from an occasional instance of re-invoking the UI thread (there's a very minor performance cost, so just don't add unneeded code for it all over the place).

于 2013-03-19T16:19:15.130 回答