几个AppDomain和本机代码 [英] Several AppDomains and native code

查看:64
本文介绍了几个AppDomain和本机代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C#应用​​程序正在使用不是线程安全的本机代码.

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.

我的问题是,我可以代替使用App Domains,以便每个位于不同App Domain上的多个托管线程将调用本机代码,并且它们不会互相干扰吗?

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.

推荐答案

是可以做到的,但您应该认真衡量是否付出的努力能回报一切.

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

Windows不会加载 unmanaged DLL的多个副本,并且非托管DLL是按进程(而不是按AppDomain)加载的.您可以做的是创建同一DLL的多个临时副本,然后用LoadLibrary()加载它们.

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().

每个进程都将被加载,但是它们将彼此分开(因此它们是线程安全的).所有这些东西都可以绑在包装非托管调用(LoadLibraryFreeLibraryGetProcAddress和调用本身)的类内.它会使用更少的资源,并且比多个进程要快,但是您必须放弃DllImport使用.

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).

这篇关于几个AppDomain和本机代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆