Multiple AppDomains and Native Code

My C # application uses native code that is not thread safe.

I can run several processes of this native code using interprocess communication to achieve concurrency.

My question is, can I use application domains instead, so that multiple managed threads, each in a different application domain, will call their own code and they will not interfere with each other?

The main goal is to prevent process separation.

+8
multithreading c # native appdomain
source share
2 answers

Yes , it can be done, but you must seriously measure if the efforts are offset by benefits.

Windows will not load multiple copies of the unmanaged DLL, and unmanaged DLLs will load in one process (not the AppDomain ). What you can do is create several temporary copies of the same DLL and then load them using LoadLibrary() .

Each of them will be loaded for each process, but they will be separated from each other (so that they are thread safe). All this can be connected inside a class that wraps unmanaged calls ( LoadLibrary , FreeLibrary , GetProcAddress and the call itself). It will use less resources and it will be faster than several processes, but you will have to abandon the use of DllImport .

The only thing I see is that it will be much better than several processes (because it uses less resources), of course, if you reuse instances that store the cache (it is more difficult to store the process cache than the object cache).

+3
source share

No, AppDomains is a concept with clean, managed code. It achieves isolation, preserving the individual roots of the managed entity. One AppDomain cannot see the objects of another, making it very safe to cancel code and unload assemblies. In no case do not delete all data that may contain state.

Unmanaged code is completely agnostic of the GC heap and, therefore, AppDomains, it will allocate its own native heap (HeapAlloc) in its data section. Such distributions are global processes. This makes the isolation boundaries process, you need an auxiliary process that loads the DLL and talks to it with one of the mechanisms of the .NET process interaction (socket, named pipe, memory mapped file, remote access, WCF).

Technically, you can create copies of DLLs, each of which has a different name. But this is very small, and pinvoke is very inconvenient, since you can no longer use [DllImport]. To initialize delegate objects, you need to declare a delegate for each exported function and LoadLibrary () and GetProcAddress ().

+9
source share

All Articles