【问题标题】:DataBinding Grid with data from another thread使用来自另一个线程的数据的 DataBinding Grid
【发布时间】:2012-07-28 05:47:37
【问题描述】:

我有一个数据结构(bindingList),它从另一个线程接收数据,我已经绑定到一个引发跨线程异常的 dataGridView。如何调用 dataGridView 是 dataBound?这是一个winForm项目。为了清楚起见,这是我正在谈论的示例:

DataStore dStore = new DataStore();
dStore.ReceiveData += new ReceiveDataEventHndlr(data);
BindingList<mydataobj> myDataStructure = new BindingList<mydataobj>();
dataGridView.DataSource = myDataStructure;

// here's my cross threading issue
private void data(string s, double d)
{
    myDataStructure.Add(new MyDataObj(s,d));
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    从另一个线程修改控件时需要使用Control.Invoke

    private void data(string s, double d)
    {
        if (this.InvokeRequired) {
            this.Invoke(new Action( () => {data(s, d);} ));
            return;
        }
        myDataStructure.Add(new MyDataObj(s,d));
    }
    

    首先,您检查是否有Control.InvokeRequired。如果是这样,则调用 Invoke() 并委托同一函数,然后返回。它将从GUI线程重新进入函数,InvokeRequired将变为false,控件将被更新。

    【讨论】:

    • 哦,好吧...我不知道调用 dataStructure 会解决这个问题。我以为我必须调用 dataGridView
    • 不,你知道。你我在控件上调用Invoke(dataGridView)
    • 我不明白。也许我应该澄清更多:我的 dataGridView 在我的表示层(GUI)中。 myDataStructure 和 dStore 在我的业务逻辑层 (BAL) 中。除了通过 dataBinding 之外,我的 dStore 和 myDataStructure 不会与我的 dataGridView 交互...将 myDataStructre 传递给 GUI 进行绑定,仅此而已。
    • 嘿,感谢您的解决方案。我现在明白了。是的,你给我的那个例子是正确的方法。再次感谢!
    • 该示例也是使用 LINQ 和通用委托的干净和更新的“.NET 建议”方法。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多