我有公共(public)静态类MyGlobals
用于我的应用程序范围变量以及处理和更改这些变量的多个线程。
public static class MyGlobals
{
public static BindingList<Device> devicesList;
public static BindingList<Device> availableList;
public static object listLock = new object();
}
我有一个 Timer
线程,用于更新部分列表(例如 Device.status
字段)以及这些列表绑定(bind)到 DataGridView 的 UI 线程
表和某些字段(例如 Device.description
字段)可以在那里手动编辑。
我的问题是,当计时器线程想要更新绑定(bind)列表内容时,我得到 InvalidOperationException
:
Additional information: Cross-thread operation not valid: Control 'gridView1' accessed from a thread other than the thread it was created on.
我在修改 MyGlogals
列表的每个代码块周围使用 lock(listLock)
语句,但我无法控制 DataGridView
处理列表的方式。如何使这个应用程序线程安全?
最佳答案
GUI本身需要从GUI线程(主线程)进行更新。 .NET 提供 BackgroundWorker类就是为了这个目的。与 GUI 的通信可以通过 ProgressChanged 来完成和 RunWorkerCompleted事件,您可以在其中传递选择的对象(例如要显示的对象)。
关于c# - 具有 BindingList<T> 和 DataGridView 的多线程 C# 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18759376/