问题很简单,我有 GUI c#/xaml 应用程序,我想在一个线程中运行 GUI,并在另一个线程中运行某种方法(无限循环)。 我需要从第二个线程修改 GUI(列表框)中的元素。 我尝试创建全局变量和来自网络的其他一些提示,但没有运行良好。
现在我有类似的东西:
public delegate void InvokeDelegate(listdata Mujlist);
//in global scope
// and in Window class
public void UpdateList(listdata Mujlist)
{
mujlistbox.DataContext = Mujlist;
}
// and in the second thread this
object[] obj = new object[1];
obj[0] = Mujlist;
mujlistbox.BeginInvoke(new InvokeDelegate(UpdateList), obj);
这可能做得很好,但我不能尝试这个,因为 VS 2010 发现错误
Error 1 'System.Windows.Controls.ListBox' does not contain a definition for 'BeginInvoke' and no extension method 'BeginInvoke' accepting a first argument of type 'System.Windows.Controls.ListBox' could be found (are you missing a using directive or an assembly reference?) D:\..\MainWindows.xaml.cs 85 28 WPFChat
但是 System.Windows.Forms 有这个 method ,所以我对 this 感到困惑.
所以,问题是如何从子线程简单地更新“GUI 线程”中的列表框?
我哪里出错了?有更好的方法吗?怎么办?
最佳答案
对于 WPF,您需要使用 Dispatcher.BeginInvoke
方法。
同时ListBox
是一个 UIElement
,它不包含 BeginInvoke
方法,它确实派生自 DispatcherObject
。因此,它有 Dispatcher
您可以使用该属性来访问Dispatcher
:
mujlistbox.Dispatcher.BeginInvoke(new InvokeDelegate(UpdateList), obj);
关于c# - 多线程可访问 "shared"列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12865512/