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
- Categories: .NET, Software Development, Multithreaded, Thread Local Storage, Platform Invoke
- Additional keywords: threadID, Win32, DLL, P/Invoke, reentrant, thread affinity, DllImport
- Technorati Tags:
software development,
.NET,
P/Invoke,
Platform Invoke,
marshalling,
thread local storage,,
BeginThreadAffinity