gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:24:16 26 4
gpt4 key购买 nike

问题很简单,我有 GUI c#/xaml 应用程序,我想在一个线程中运行 GUI,在另一个线程中运行一些方法(无限循环)。我需要从第二个线程修改 GUI ( listbox ) 中的元素。我尝试创建全局变量和来自网络的一些其他提示,但没有任何运行良好。

现在我有这样的东西:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com