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


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Thursday, January 10, 2008 9:14 AM | in .NET Software Development

Comments

No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 3 and 1 and type the answer here: