Load Dll multiple times to allow multi threading in .Net

好久不见. 提交于 2019-11-29 14:27:16

The workaround you found is actually a pretty decent one. There might be small odds that LoadLibraryEx() with the LOAD_LIBRARY_AS_IMAGE_RESOURCE option will work. That option allows you to load it multiple times. I seriously doubt it though, the DLL almost certainly relies on getting its runtime support code initialized through DllMain.

One thing I didn't hear you mention is the pain of having to use GetProcAddress(). Make sure you do or you'll still stomp global variables when you start threading. Each thread must use its own address.

Loading the DLL is not the way to create a thread. Your two options are to use AppDomains or outright separate processes.

The easy way to do it might be to simply use a master/slave arrangement, where the logic that uses the library is all done in the slave process. The master kicks off as many "slaves" as it wants or needs, and then collects the return values.

Write the code in the "slave" as if it is single threaded, because... it is.

Use System.Diagnostics.Process.Start from the master, to launch these things.


In general, copying the DLL and loading all the copies is not a failsafe approach; the DLLs themselves may access OS resources like mutexes or even lockfiles. These won't be aware that the copies are supposed to be "separate".

If your library is purely a compute library and you REALLY REALLY want to do the copy-and-load-the-copies approach, you can create hardlinks to avoid having to duplicate the actual DLL file. (fsutil hardlink create on Win7 or Vista)

Dominik Fretz

As you figuered out, you cannot load the library multiple times. I guess you have two possibilities:

In both solutions you need to consider a method of data exchange betwen the processes/app domains. Anyway, it won't be a simple task!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!