|
CIS 573
Thread attributes
last updated: 08/07/2006 |
[STAThread] and [MTAThread] STAThread stands for SingleThreadApplicationThread, meaning that your application is limited to its own single thread. This is required for certain things like Dynamic menu items to work in Win98/ME. Including the [STAThread] attribute indicates that the default threading model for an application is single-threaded apartment (STA). Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread safe. Threading models only pertain to applications that use COM interop. Applying this attribute to an application that does not use COM interop has no effect. The startup threading model can be set to single-threaded apartment or multithreaded apartment. If it is not set, then the thread is not initialized. WMI provider COM objects are "free" threaded, that means they need to run in a MTA thread. When your main thread is initialized for STA, the Management classes check the current apartment for MTA compatibility, and will create a new thread and enter the MTA to create the COM objects, COM will marshal the interfaces between the STA thread (running your managed code) and the MTA thread running the native COM code. But, your main thread (STA) has enabled the SeSecurityPrivilege for the main thread, but this privilege is not propagated to the MTA thread, resulting in an access denied exception. Therefore I suggest you allways run your code on an MTA thread, the net benifits are - no marshaling overhead - no difficult to track security issues. - no issues due to eventsink marshalin between MTA and STA threads. There is a known bug in System.Management.dll in .NET Framework v1.0. The bug that prevents WMI privileges from propagating from managed code running on STAThread to WMI core. Applying [MTAThread] to the calling thread appears to be a partial workaround to this problem as Access Denied would still be returned on the second time of event subscription. This problem should be fixed in .NET Framework v1.1. Have you tried running your application with v1.1?