我有一个监听数据的单独线程。在接收一些数据时,它需要访问应用程序中的一个窗口并为该窗口设置一些字段。
现在当我使用它时会抛出异常(说这个线程无法访问,因为Windows1归其他线程所有):
foreach (Window w in App.Current.Windows)
{
if (w.Name == "WindowIamInterested")
{
//w.SetField set some fields in the window and
//and do w.Show() or w.Activate() to show the window to user
}
}
上面的代码在一个单独的线程中运行,而不是主线程。 有没有办法可以访问和修改窗口。
答案 0 :(得分:2)
您在寻找窗口的dispatcher吗?您可以从窗口获取调度程序,并要求他通过Dispatcher.Invoke()或Dispatcher.BeginInvoke()执行您的代码......
答案 1 :(得分:1)
如果您正在使用WPF控件,则可以使用其调度程序在UI线程上安排更新:
myControl.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal
, new System.Windows.Threading.DispatcherOperationCallback(delegate
{
// update control here
return null;
}), null);
如果您需要阻止直到控件更新,您将使用Invoke()
,否则您应该使用BeginInvoke()
。
答案 2 :(得分:1)
您可以使用Dispatcher.Invoke:
Application.Current.Dispatcher.Invoke(
(ThreadStart)delegate
{
// do your UI work here
});
Dispatcher.Invoke
同步执行。如果要异步执行,可以使用Dispatcher.BeginInvoke。