Wednesday, February 3, 2010

Complex bugs and multithreading

If you are using unit test, you should know that every test is executed on it’s own thread. Last week I had a strange error where two tests failed(sometimes).

Both tests were using an EventWaitHandle to do some synchronizationruns. If I both tests by themselves, the test run was successful. However, if ran them together, then I got the following error:

Test method threw exception: System.ObjectDisposedException: Safe handle has been closed.

I found out that the two tests were sharing an EventHandler. The first test raises an event and dispose itself. But in my code I never unattached the event handler. So when the second test raises the event, the eventhandler still thinks that there are 2 methods to call, not just one.

After changing the code to properly detach the event, everything was working. So unittests are also a good test to check if your code is thread-safe.

No comments: