我在多线程环境中遇到单例类问题。该示例程序调用方法A& B在不同的线程上。通常这可行。
在某些情况下,如最后一个结果所示
这是因为我没有表演双锁吗? 我如何确保不会发生这种情况?
呼叫者
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(CallonThread));
Singleton.Instance.Test("B");
Console.ReadKey();
}
static void CallonThread(object a)
{
Singleton.Instance.Test("A");
}
}
Singleton Class
public class Singleton
{
static readonly object Padlock = new object();
private static Singleton _instance;
protected Singleton()
{
}
public static Singleton Instance
{
get
{
lock (Padlock)
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
public void Test(string id)
{
if (id == "A")
{
new Data().MethodA();
}
else
{
new Data().MethodB();
}
}
}
数据类
public class Data
{
public void MethodA()
{
Console.WriteLine("Start Method A");
Console.WriteLine("End Method A");
}
public void MethodB()
{
Console.WriteLine("Start Method B");
Console.WriteLine("End Method B");
}
}
答案 0 :(得分:2)
这可以阻止MethodA和MethodB同时执行:
public class Data
{
private static object _padlock = new object();
public void MethodA()
{
lock (_padlock)
{
Console.WriteLine("Start Method A");
Console.WriteLine("End Method A");
}
}
public void MethodB()
{
lock (_padlock)
{
Console.WriteLine("Start Method B");
Console.WriteLine("End Method B");
}
}
}