InvalidCastException when you call a COM component that is marked as STA

Article translations Article translations
Article ID: 309330 - View products that this article applies to.
This article was previously published under Q309330
Expand all | Collapse all

SYMPTOMS

When you call a Component Object Model (COM) component that has been marked as single-threaded apartment (STA), you may receive an instance of InvalidCastException or experience errors in marshaling parameters and return values.

CAUSE

By default, a managed thread is initialized as multithreaded apartment (MTA). If a COM component is marked as STA, a proxy (or stub DLL) or automation-compatible Type Library file must be registered to properly communicate with it from an MTA thread.

RESOLUTION

To resolve this issue, use either of the following methods:
  • Create a new STA thread in the client code, and then set its ApartmentState property to STA. Then, call a COM component from this thread.

    -or-
  • Declare a managed client as STA by applying the STAThread attribute on the main method, if doing so does not affect other calls to unmanaged code.
If you want to maintain the MTA model of the client application, use either of the following methods:
  • Register a Type Library file if the COM component is OLE Automation-compatible.
  • Register a proxy, or stub DLL, generated from the Interface Definition Language (IDL) file.

STATUS

This behavior is by design.

REFERENCES

Managed and Unmanaged Threading
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconmanagedunmanagedthreading.asp

Properties

Article ID: 309330 - Last Review: April 8, 2009 - Revision: 4.0
APPLIES TO
  • Microsoft .NET Framework 3.5
  • Microsoft .NET Framework 3.0
  • Microsoft .NET Framework 2.0
  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 1.0
Keywords: 
kbmarshal kbcominterop kbbug kbreadme KB309330

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com