Binary Artist

The Jason Marshall Experience

Binary Artist

Jason Marshall
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

When Multi threading unsafe COM Win32 code always specify a seperate apartment model

A .NET thread is automatically assigned an apartment upon entering apartment-savvy Win32 or legacy COM code. By default, it will be allocated a multi-threaded apartment, unless one requests a single-threaded apartment as follows:
 Image Preview
Thread t = new Thread (...);
t.SetApartmentState (ApartmentState.STA);
One can also request that the main thread join a single-threaded apartment using the STAThread attribute on the main method:
class Program {
  [STAThread]
  static void Main() {
  ...
Apartments have no effect while executing pure .NET code. In other words, two threads with an apartment state of STA can simultaneously call the same method on the same object, and no automatic marshalling or locking will take place. Only when execution hits unmanaged code can they kick in.The types in the System.Windows.Forms namespace extensively call Win32 code designed to work in a single-threaded apartment. For this reason, a Windows Forms program should have have the [STAThread] attribute on its main method, otherwise one of two things will occur upon reaching Win32 UI code:
  • it will marshal over to a single-threaded apartment
  • it will crumble and fail.

Posted by Admin on Wednesday, April 30, 2008 4:29 AM
Permalink | Comments (0) | Post RSSRSS comment feed
Free Hit Counters
page counter