工作线程添加到BindingList时的跨线程操作异常

C W*_*ker 5 c# data-binding multithreading bindinglist winforms

我有一个需要添加项目的工作线程BindingList.但是,BindingList数据绑定为a DataGridView.所以,当我尝试添加到列表中时,我得到了一个InvalidOperationException (Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.)

通常,对于此例外,您可以:

if(winformControl.InvokeRequired) {
    winformControl.Invoke(MethodDelegate);
}
Run Code Online (Sandbox Code Playgroud)

然而,数据绑定会使事情变得混乱,因为看不到Winform控件.我只有以下行,它抛出异常:

ClassInstance.MyBindingList.Add(myObject);
Run Code Online (Sandbox Code Playgroud)

如果你有专门针对这种情况的解决方案,那很好.

如果没有,我怎样才能让工作线程告诉我的主线程执行一个特定的方法(工作线程提供了几个参数)?这可能是一个更好的选择,因为我的工作线程实际上正在做一堆东西(比如写入数据库),而且我不确定一切是否是线程安全的.我是一名学生,也是多线程的新手,而且这真的不是我的强项.

Chr*_*isF 0

您可以向主、UI、线程触发一个事件,其中有:

if (this.InvokeRequired)
{
    this.Invoke(...);
}
Run Code Online (Sandbox Code Playgroud)

所以您正在主窗口本身上进行测试。