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

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

问题描述

我的 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.

我的问题是,我可以改用应用程序域,以便多个托管线程(每个位于不同的应用程序域)调用本机代码并且它们不会相互干扰吗?

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 不会加载 非托管 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).

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

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