c# - 多线程可访问 "shared"列表框

标签 c# multithreading visual-studio-2010 user-interface listbox

问题很简单,我有 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/

相关文章:

c - 反向传播算法的多线程

java - newFixedThreadPool() 与 newCachedThreadPool()

c# - 如何打破 UnitTesting.Assert.AreEqual?

visual-studio-2010 - 我可以使用一个许可证在两台机器上安装 VS 吗?

c# - XML 命名空间 'ContentPage' 中的未知类型 'http://xamarin.com/schemas/2014/forms'

c# - 限制文件/文件夹写入指定根以外的路径

c# - 如何以编程方式更改桌面/文件夹图标大小 C#

c# - 访问 EventHandler 中的 RepeaterItem 控件

ruby - 共享互斥体的交替例程

c++ - 单色位图 C++ GDIPlus