具有多个 DLL 的 c# 单例模式
c# Singleton Pattern with multiple DLLs
我的问题是关于在以下程序集和库群中使用的单例模式。
想象一下以下程序集
- CommonLibrary.dll
- MainProcess.exe
- Plugin1.dll
- Plugin2.dll
MainProcess.exe、Plugin1.dll 和 Plugin2.dll 使用 CommonLibrary.dll 中的 class Manager
。 CommonLibrary.dll 在编译时链接到其他程序集。 Manager
class 使用单例模式:
public class Manager
{
private static Manager instance;
public static Manager Instance
{
[MethodImpl(MethodImplOptions.Synchronized)]
get {
if (instance == null)
{
instance = new Manager();
}
return instance;
}
}
private Manager()
{
}
// methods ...
}
单例模式仅用于创建 Manager
class 的一个实例(很明显)。这在Manager
的方法中很重要,因为对资源的访问需要用不同的锁来协调。例如。通过使用锁:
// Method inside Manager
public void DoSomething()
{
lock(someLockObject)
{
// do something
}
}
MainProcess.exe、Plugin1.dll 和 Plugin2.dll 通过调用
在代码中的某处引用了管理器
Manager manager = Manager.Instance;
// do something with manager
现在想象一下以下场景:
MainProcess.exe 在运行时使用 Assembly.LoadFrom();
使用反射加载 Plugin1.dll 和 Plugin2.dll
问题:MainProcess.exe、Plugin1.dll 和 Plugin2.dll 是否共享 相同的 Manager 实例?这很重要,因为如果他们不共享同一个管理器实例,我需要对资源进行一些进程间锁定。
谢谢。
Do MainProcess.exe, Plugin1.dll, and Plugin2.dll share the same instance of Manager?
是的,他们有。在应用程序域中将只有一个 Manager
实例(并且在整个过程中,除非您显式创建另一个 AppDomain
)。
我的问题是关于在以下程序集和库群中使用的单例模式。
想象一下以下程序集
- CommonLibrary.dll
- MainProcess.exe
- Plugin1.dll
- Plugin2.dll
MainProcess.exe、Plugin1.dll 和 Plugin2.dll 使用 CommonLibrary.dll 中的 class Manager
。 CommonLibrary.dll 在编译时链接到其他程序集。 Manager
class 使用单例模式:
public class Manager
{
private static Manager instance;
public static Manager Instance
{
[MethodImpl(MethodImplOptions.Synchronized)]
get {
if (instance == null)
{
instance = new Manager();
}
return instance;
}
}
private Manager()
{
}
// methods ...
}
单例模式仅用于创建 Manager
class 的一个实例(很明显)。这在Manager
的方法中很重要,因为对资源的访问需要用不同的锁来协调。例如。通过使用锁:
// Method inside Manager
public void DoSomething()
{
lock(someLockObject)
{
// do something
}
}
MainProcess.exe、Plugin1.dll 和 Plugin2.dll 通过调用
在代码中的某处引用了管理器Manager manager = Manager.Instance;
// do something with manager
现在想象一下以下场景: MainProcess.exe 在运行时使用 Assembly.LoadFrom();
使用反射加载 Plugin1.dll 和 Plugin2.dll问题:MainProcess.exe、Plugin1.dll 和 Plugin2.dll 是否共享 相同的 Manager 实例?这很重要,因为如果他们不共享同一个管理器实例,我需要对资源进行一些进程间锁定。
谢谢。
Do MainProcess.exe, Plugin1.dll, and Plugin2.dll share the same instance of Manager?
是的,他们有。在应用程序域中将只有一个 Manager
实例(并且在整个过程中,除非您显式创建另一个 AppDomain
)。