简体   繁体   中英

LoadLibrary failing with code 126 except when stepping through the code

I'm loading opencv dlls dynamically using LoadLibrary. The operation fails frequently when letting the code run, but succeeds when stepping through the code.

Here is how I import the dlls

[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("Kernel32.dll")]
static extern uint SetErrorMode(uint uMode);
[DllImport("Kernel32.dll")]
static extern uint GetLastError();

const uint SEM_FAILCRITICALERRORS = 0x0001;

Here is the code used to load the dlls.

// called once
SetErrorMode(SEM_FAILCRITICALERRORS);

// called for each dll string name in a loop
var p = Path.Combine(opencvDirectory, filename);
LoadLibrary(p);
var error = GetLastError();
// repeat with next file

I have tried putting a Thread.Sleep(1000); before each line, which does not help. If I break on, and step over LoadLibrary(p); , it succeeds every time. It seems to make no difference how much time I wait before stepping over the line.

If it matters, I am loading 45 opencv dlls. When I repeat the automatic loop, it loads the first 12 in the list, then the next 6, then it won't load any more on any subsequent run (27 remaining). This appears to be consistent. However if I step over the code at this point, file by file, I am able to load all the rest.

I am running 64 bit Windows 7, and my application is targeting x86.

Does anyone have an idea why this happens, and how to fix it?

I added a Thread.Sleep(50) for each iteration (dll), and an Application.DoEvents() before each API call like this

Thread.Sleep(50);
Application.DoEvents();
LoadLibrary(p);
Application.DoEvents();
var error = GetLastError();

and now the dlls are all loaded after a few passes through consistently.

The whole operation just takes a little longer than I would like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM