我在 Windows 窗体
应用程序中使用了这个函数:
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
中它不起作用。为什么?
在 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();
}