Application.DoEvents are evil

It is no small wonder that the MSDN reference page for the Application.DoEvents method comes with a (somewhat dire) warning:

If a message causes an event to be triggered, then other areas of your application code may execute. This can cause your application to exhibit unexpected behaviors that are difficult to debug.

Consider the following code fragment:

SomeType value;
if (dictionary.TryGetValue(key, out value))
  return value;
else
{
  value = SomeCoolCreateMethod();
  dictionary.Add(key, value);
}

Can you spot a bug in the code? Do not worry if you cannot, but it is there alright. Imagine if this code is part of an event handler for some action and then imagine that the method SomeCoolCreateMethod initiates complex operation that deep down in some method calls DoEvents. If the user performed that action two times in a small time frame, smaller than the time needed to finish the SomeCoolCreateMethod method, you might get an exception in the line 7 saying that the item is already part of the dictionary.

So remember that calling DoEvents has its cost in the long run. And if you see such strange exceptions occurring in your code, check if deep down the DoEvents method is called.

About programabilan

Profesionalni programer, amaterski programer...

Posted on November 16, 2011, in Tips and tagged , . Bookmark the permalink. Leave a comment.

Leave a comment