Sucky MSTest and the "WaitAll for multiple handles on a STA thread is not supported" Error
        Posted  
        
            by Anne Bougie
        on Geeks with Blogs
        
        See other posts from Geeks with Blogs
        
            or by Anne Bougie
        
        
        
        Published on Wed, 07 Apr 2010 16:59:50 GMT
        Indexed on 
            2010/04/07
            18:03 UTC
        
        
        Read the original article
        Hit count: 684
        
If you are doing any multi-threading and are using MSTest, you will probably run across this error. For some reason, MSTest by default runs in STA threading mode. WTF, Microsoft! Why so stuck in the old COM world? When I run the same test using NUnit, I don't have this problem. Unfortunately, my company has chosen MSTest, so I have a lot of testing problems. NUnit is so much better, IMO.
After determining that I wasn't referencing any unmanaged code that would flip the thread into STA, which can also cause this error, the only thing left was the testing suite I was using. I dug around a little and found this obscure setting for the Test Run Config settings file that you can't set using its interface. You have to open it up as a text file and add the following setting:
<ExecutionThread apartmentState="MTA" />
This didn't break any other tests, so I'm not sure why it's not the default, or why there is nothing in the test run configuration app to change this setting.
Here is the code I was testing:
public void ProcessTest(ProcessInfo[] infos)
{
WaitHandle[] waits = new WaitHandle[infos.Length];
int i = 0;
foreach (ProcessInfo info in infos)
{
AutoResetEvent are = new AutoResetEvent(false);
info.Are = are;
waits[i++] = are;
Processor pr = new Processor();
WaitCallback callback = pr.ProcessTest;
ThreadPool.QueueUserWorkItem(callback, info);
}
WaitHandle.WaitAll(waits);
}
© Geeks with Blogs or respective owner