.NET: Multithreaded Platform Invoke and Unmanaged Thread-Local Storage

by Stephen Horsfield 10. January 2008 09:14

Overview

I came across this problem when trying to help someone with multithreaded P/Invoke calls to an unmanaged DLL.  This DLL had previously worked with unmanaged (Win32) applications.

Note that this post does not apply to consuming COM objects.

The problem

Instead of working, the second time the DLL was invoked would cause an unmanaged exception.

The reason

In Win32, each thread has a thread ID and DLLs create thread-specific storage which relate to these thread IDs.  However, in .NET, each managed thread can use any of a pool of unmanaged threads and so there isn't a guarantee as to which unmanaged thread ID is used to execute a particular DLL call.  This means that if you have multiple .NET threads attempting to use a multithreaded DLL then you will hit problems.

The solution

The .NET team anticipated this issue and designed the Thread.BeginThreadAffinity method.  You should use this in any thread that needs to be tied to a specific Win32 thread.  Remember to call EndThreadAffinity when finished!

References

Versions

  • Microsoft .NET Framework 2.0

Metadata

Tags:

Software Development

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar