Why profiler API causes my .NET application to run as STA?

It seems I’m in a tip giving mood this week. I’d like to tell a story of a bug we had in Isolator…

 

Last a user complained about a bug that prevented one of VS2010 cronies to work properly. After investigating this issue he found out that using Isolator caused this code:

[MTAThread()]
static void Main(string[] args)
{
Console.WriteLine(Thread.CurrentThread.ApartmentState.ToString());
}

To write STA on screen. It seems that running along with Isolator caused the thread apartment to transfer from MTA (Multiple Threaded Apartments) to STA (Single Threaded Apartments).Question Mark and Arrow by laurakgibbs.

 

I’d like to take a minute to thank two people:

the customer that took the time to investigate this issue and David Broman.

 

For those of you who are not familiar with the .NET profiler API – it’s a cool API that enable us developers interact with the .NET framework in a low level way (read: C++) extract information and manipulate the running .NET code. One thing it really lacks – is good documentation, in fact if you do want to use it you would probably end up reading David’s blog.

In Typemock we use the profiler API to do our “magic” of faking actual, honest-to-god .NET objects so when I saw this strange issue I concluded that it could only be cause by some bug we have in how we use the Profiler API.

After a bit of tinkering I understood one thing – I had no idea what went wrong here, perhaps it could be a VS2010/.NET 4 issue?

 

I’ve decided to sent an email to David Broman asking about this issue – perhaps I’m facing a known issue with a known fix. David’s answered my question with the following:

1. This is not a known issue

2. Send me a repro and I’ll investigate it

 

To cut a long story short I’ve wrote a simple example and David investigated it and found that we had a bug – the profiler API is a COM object and as such we’ve used CoInitialize(0)  which seemed the right thing to do at the time – unfortunately it also sets the thread apartment as well!

Because we want to application running to set the thread apartments we should not call CoInitialize from the profiler.

 

Needless to say now everything works just fine. I hope I didn’t bore you too much and that this information was helpful for at least one of you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s