BUG: InvalidCastException When You Call a COM Component That Is Marked as STA (309330)



The information in this article applies to:

  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 1.0

This article was previously published under Q309330

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

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

Modification Type:MajorLast Reviewed:4/8/2003
Keywords:kbMarshal kbCOMInterop kbbug kbreadme KB309330