我有简单的单例类:在单新线程永远不会结束
namespace TestApp
{
public class MySingleton
{
static MySingleton()
{
}
private static readonly MySingleton instance = new MySingleton();
private bool threadFinished = false;
public bool IsReady = false;
private MySingleton()
{
Thread t = new Thread(MyAction);
t.Start();
while (!threadFinished)
Thread.Sleep(10);
}
public static MySingleton Instance
{
get { return instance; }
}
private void MyAction()
{
threadFinished = true;
}
}
}
当我试图instatiate这种情形:
var ir = MySingleton.Instance.IsReady;
它永远不会结束 - while循环是无限的。为什么?以及如何在构造函数中在单例中运行backround线程?
它可以将threadFinished声明为volatile,但请google改为更好的单例模式。 – fhogberg