Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are LoadLibrary, FreeLibrary and GetModuleHandle Win32 functions thread safe?

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

like image 626
oscarkuo Avatar asked Jun 28 '12 22:06

oscarkuo


1 Answers

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). HBITMAPs, HICONs 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.

like image 164
Eric des Courtis Avatar answered Oct 06 '22 01:10

Eric des Courtis