I have a static DataLibrary class that implements a singleton pattern.
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;
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.)