Hadar Grubman Hadar Grubman - 1 year ago 108
C# Question

Several AppDomains and native code

My C# application is using native code which is not thread safe.

I can run multiple processes of that native code, using inter-process communication to achieve concurrency.

My question is, can i use App Domains instead, so that several managed threads, each on a different App Domain, will call the native code and they will not interfere with each other?

The main goal is to prevent process seperation.

Answer Source

Yes it can be done but you should seriously measure if effort is repaid by benefits.

Windows won't load multiple copies of an unmanaged DLL and unmanaged DLLs are loaded per-process (not per AppDomain). What you can do is to create multiple temporary copies of same DLL then load them with LoadLibrary().

Each one will be loaded per-process but they'll be separated from each other (so they'll be thread-safe). All this stuff can be tied inside a class that wraps unmanaged calls (LoadLibrary, FreeLibrary, GetProcAddress and invocation itself). It'll use less resources and it'll be faster than multiple processes but you'll have to drop DllImport usage.

The only benefit I see is that this will scale much better than multiple processes (because it uses less resources) of course if you reuse instances keeping a cache (it's harder to keep a process cache than an object cache).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download