我有一个静态的DataLibrary类实现了单例模式。C#线程静态变量
public static FacilityRepository FacilRepo
{
get
{
if (_facilRepo == null)
{
_facilRepo = new FacilityRepository(Authenticated.UserId);
if (Authenticated.FacKey.Length > 0)
{
foreach (var fac in _facilRepo)
fac.IsSelected = (fac.FacilityKey == Authenticated.FacKey);
}
}
return _facilRepo;
}
}
private static FacilityRepository _facilRepo;
当使用Task.Factory.StartNew的FacilityReposity被重建多次,我怎样才能避免这种情况我访问此从不同的线程。
如果您同时创建许多新线程,并且它们都尝试访问FacilRepo属性,则可能是因为该属性没有锁定。看看http://en.csharp-online.net/Singleton_design_pattern%3A_Thread-safe_Singleton(在底部) – WiseGuyEh 2011-03-17 15:03:18