Microsoft Knowledge Base Article
This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved.
Terms
of Use |
Trademarks
Article ID: 309330 - Last Review: April 8, 2009 - Revision: 4.0
InvalidCastException when you call a COM component that is marked as STA
This article was previously published under Q309330
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.
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.
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.
This behavior is by design.
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
| kbmarshal kbcominterop kbbug kbreadme KB309330 |
Community Feedback System
Very often, it takes hours to solve a problem. Very often, you've looked high
and low, and have tried a lot of solutions. When you finally found it, chances
are, it was because someone else helped you. Here's your chance to give back.
Use our community feedback tool to let others know what worked for you and what
didn't.
Please also understand that the community feedback system is not warranted to be
correct, it's simply a system that we've built to let people try and help each
other. If something in a feedback response doesn't make sense to you, or you're
not comfortable making changes that the feedback talks about (like registry
edits), please consult a professional.
Thank you for using kbAlertz.com Feedback System.
-- Scott Cate