简体   繁体   English

绑定到Dictionary并使用线程更新的DataGridView

[英]DataGridView bound to a Dictionary and updated with a thread

I have a Dictionary bound to DataGridView by using following sample code. 通过使用以下示例代码,我有一个绑定到DataGridView的Dictionary。

DataGridView bound to a Dictionary 绑定到字典的DataGridView

Please see the above question first 请首先查看上述问题

The diffrence is that i am updating dictionary from a thread. 不同之处在于我正在从线程更新字典。 (Event handler of another class). (另一个类的事件处理程序)。

My Event handler is as below 我的事件处理程序如下

static void f_PriceChanged(Objet f, eventData e)
{

    if (prices.ContainsKey(e.ItemText))
        prices[e.ItemText] = e.price;
    else
        prices.Add(e.ItemText, e.price);

}

Not to mention the prices is declared as class level. 更不用说价格被宣布为班级。

I have modified the button code from original post as 我已经将原始帖子中的按钮代码修改为

    Button btn = new Button();
    btn.Dock = DockStyle.Bottom;
    btn.Click += delegate
    {                
        bl.Reset();
    };
    form.Controls.Add(btn);

Internally the Dictionary is updated as expected but grid does not update. 在内部,字典已按预期更新,但网格未更新。 Clicking on button generate exception 点击按钮产生异常

Collection was modified; 集合已修改; enumeration operation may not execute 枚举操作可能无法执行

What to do? 该怎么办?

You have to use a lock statement to protect your shared resource : the dictionary. 您必须使用lock语句来保护共享资源:字典。

private object _lock = new object();

private void Reset()
{
    lock(_lock)
    {
        // your code here
    }
}

void f_PriceChanged(Objet f, eventData e)
{
    lock(_lock)
    {
        if (prices.ContainsKey(e.ItemText))
            prices[e.ItemText] = e.price;
        else
            prices.Add(e.ItemText, e.price);
    }

}

You'll have to make f_PriceChanged() a member. 您必须使f_PriceChanged()成为成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM