void CommandHandler()
{
if (InvokeRequired)
{
/* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */
BeginInvoke(new AsynchronousSocketListener.ReadHandler(CommandHandler));
return;
}
else
{
//do UI thread code here
}
}
5 回答
您想使用Dispatcher.Invoke方法 .
如果你的
this
是DependencyObject
类,你可以简单地使用它:您无法直接从单独的GUI元素访问(例如,从线程池中拉出异步操作或直接使用Thread类创建) . 您需要做的是通过调度员执行您的操作,如下所示:
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => slider.Text = "mystuff"));
有关Dispatcher如何管理线程的更多信息,请参阅下面的MSDN链接:
http://msdn.microsoft.com/en-us/library/vstudio/system.windows.threading.dispatcher
找到完全在UI线程中创建回调函数的解决方案(CommandHandler是MainForm中的方法,并从AsynchronousSocketListener的另一个线程调用):
对于那些可能需要工作示例的人,在Basler Pylon 4.0库示例程序PylonLiveView中以这种方式完成了这些工作 .
您应该在UI线程中调用您的代码 . 尝试使用Dispatcher
您需要使用WPF Dispatcher类将方法调用回UI线程 - 请参阅
this