tags:

views:

43

answers:

1

I have a problem with race conditions with winforms.

  listViewCollections.ItemChecked += foo //Somewhere

  void foo(object sender, ItemCheckedEventArgs e)
    {
        if (e.Item.Checked == false) return;
        bool flag = bar( e.Item.Index);
        if (flag) {
            MessageBox.Show( ... )
            e.Item.Checked = false;
       }
    }

Sometimes the message box shows twice. What's the correct way to do this? Thanks in advance!

+1  A: 

Could you not just put a simple lock around it? Also I would suggest switching the way the Checked logic works to simplify the function a little (remove the mid-function return)

private static object fooLock = new object();
void foo(object sender, ItemCheckedEventArgs e)
{
    lock (fooLock)
    {
        if (e.Item.Checked) 
        {
            if (bar(e.Item.Index)) 
            {
                MessageBox.Show( ... )
                e.Item.Checked = false;
            }
        }
    }
}

Numerous ways to improve the performance, but that should at least stop the race conditions?

mrnye