I'm working on a web service that interacts with a native DLL and I use LoadLibrary/GetModuleHandle/FreeLIbrary and GetProcAddress to dynamically load/unload the DLL because it is not very stable.
public class NativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr LoadLibrary(string libname);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string libname);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
}
I've noticed that w3wp.exe process occationally crashes under heavy load and when I tried to debug it the debugger often stops at my NativeMethods.GetModuleHandle() function call.
I couldn't find any evidence that GetModuleHandle
is not thread-safe so I'm wondering has anyone got any similar experience when interacting these kernel32.dll function from multi-threaded .NET applications?
Oscar
According to Igor Tandetnik (Microsoft MVP).
Aside from GDI functions which are not thread-safe. Almost anything that takes an HWND
and/or an HDC
must be called on the same thread where that HWND
or HDC
was created (SendMessage
, PostMessage
and similar are notable exceptions). HBITMAP
s, HICON
s and such could be passed between threads, but should be manipulated by one thread at a time.
Most other functions - those that don't deal with GDI or window management - are indeed thread-safe.
This should include LoadLibrary
, GetModuleHandle
, FreeLibrary
and GetProcAddress
.
Keep in mind however that FreeLibrary
should not be called from DllMain.
I can also add that I have been using these functions in a multi-threaded environment for quite some time without issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With