Home > Vs2012 > MTA testing on Vs2012

MTA testing on Vs2012

2013/09/11

A Visual Studio Test project, containing for example an Unit Test, is running by default in STA (Single Threaded Apartment) mode.

Then if in your code there are threading instructions as WaitHandle.WaitAll or similar , the Unit Test launch causes this error:

System.NotSupportedException: WaitAll for multiple handles on a STA thread is not supported

In the previous versions of Visual Studio (2008, 2010) it was possible to specify a test settings file , where to insert the lines

<Execution>
     <ExecutionThread apartmentState="MTA" />
</Execution>

I have tried the same approach with Visual Studio 2012 but apparently it does not work , could be that i have made some mistake.

But there is another approach, run the test forcing the MTA mode in the Unit Test code.

For example i have an [TestMethod] named TestBase : i changed TestBase as Private and deleted the [TestMethod] decoration; then i created another [TestMethod] where i launch the TestBase method in a thread, forcing the MTA mode:

[TestMethod]
public void MtaTestBase()
{
    var objThread = new Thread(new ThreadStart(TestBase));
    objThread.SetApartmentState(ApartmentState.MTA);
    objThread.Start();
    objThread.Join();
}

private void TestBase()
{
   // code that uses threading
}

With this trick my Unit Test is running without errors.

Advertisements
Categories: Vs2012
%d bloggers like this: