I have a static DataLibrary class that implements a singleton pattern.
public static FacilityRepository FacilR开发者_如何学Pythonepo
{
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;
When I access this from different threads using Task.Factory.StartNew the FacilityReposity gets recreated multiple times how can I avoid this.
I don't think you've actually got a thread-local variable here - you've just got a race condition because you're not implementing the singleton pattern properly.
I have a page about the singleton pattern which gives some better options. (In particular, as you're using the TPL you must be using .NET 4, so the Lazy<T>
option is definitely a contender.)
This Article by Jon Skeet might be helpful: Implementing the Singleton Pattern in C#
These questions might be helpful too:
- Singleton by Jon Skeet clarification
- Singleton Pattern with Public Constructor
This would happen if multiple threads access your property for the first time, before _facilRepo
is initialised. You have to lock the initialisation code like this:
private static object _facilRepoLock = new object();
public static FacilityRepository FacilRepo
{
get
{
if (_facilRepo == null)
{
lock (_facilRepoLock)
{
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;
精彩评论