我在一个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中,它不起作用。为什么?
发布于 2013-03-20 00:21:14
在WPF中,Invoke方法位于dispatcher上,因此您需要调用Dispatcher.Invoke而不是Invoke。此外,没有InvokeRequired属性,但是dispatcher有一个CheckAccess方法(由于某种原因,它隐藏在intellisense中)。所以你的代码应该是:
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-20 00:19:50
在WPF中,使用CheckAccess方法而不是InvokeRequired方法
if (!CheckAccess()) {
// On a different thread
Dispatcher.Invoke(() => log_left_accs(arg));
return;
}发布于 2013-03-20 00:19:24
检查Dispatcher.CheckAccess()
https://stackoverflow.com/questions/15504826
复制相似问题