简体   繁体   中英

DataGridView bound to a Dictionary and updated with a thread

I have a Dictionary bound to DataGridView by using following sample code.

DataGridView bound to a Dictionary

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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