C#多线程Singleton(单件)模式模板

网络编程 2021-07-04 22:40www.168986.cn编程入门
狼蚁网站SEO优化是一个C#多线程单件模式的代码模板。把T换成你自己的类型就可以使用了。其精妙之处就在于用lock语句锁定资源来避免多线程走入if语句去创建多个对象
代码如下:

private static volatile T _instance = null;
private static object objLock = new Object();
private T()
{
}
public static T Instance
{
get
{
if (_instance == null)
{
lock (objLock)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}

在必要的时候需如果要刷新当前instance,可以这样写
代码如下:

public static void RefreshInstance()
{
_instance = new T();
}

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by