繁体   English   中英

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

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

通过使用以下示例代码,我有一个绑定到DataGridView的Dictionary。

绑定到字典的DataGridView

请首先查看上述问题

不同之处在于我正在从线程更新字典。 (另一个类的事件处理程序)。

我的事件处理程序如下

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);

}

更不用说价格被宣布为班级。

我已经将原始帖子中的按钮代码修改为

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

在内部,字典已按预期更新,但网格未更新。 点击按钮产生异常

集合已修改; 枚举操作可能无法执行

该怎么办?

您必须使用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);
    }

}

您必须使f_PriceChanged()成为成员。

暂无
暂无

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

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