跨线程错误

Cross-thread mistakes

我无法用自己的话来解释,所以情况是这样的:

myBindingSource.Add(new myElement());
SetDataSource(myBindingSource);
myBindingSource.Add(new myElement());

我总是在第二次调用 Add 时捕获异常(跨线程异常)。这是 SetDataSource void:

delegate void SetDataSourceCallback(BindingSource db);
private void SetDataSource(BindingSource db)
{
        if (myDataGridView.InvokeRequired)
        {
            SetDataSourceCallback d = new SetDataSourceCallback(SetDataSource);
            myDataGridView.Invoke(d, new object[] { db });
        }
        else
        {
            myDataGridView.DataSource = db;
        }
}

我不明白为什么会这样!

使用主 UI 线程的调度程序从任何其他线程安全地调用任何 UI 代码。

WPF 不能让您从 "main" UI 线程以外的其他线程更改任何 UI 状态。所以一般来说,如果你有任何改变 UI 的状态,你应该用 Dispatcher.Invoke 代码包装它。

Application.Current.Dispatcher.Invoke(new Action(() => {
   myBindingSource.Add(new myElement());
   SetDataSource(myBindingSource);
   myBindingSource.Add(new myElement());
 }));