I have method which is generating multiple threads (lambdas) in parallel and during its execution it access Lazy field property defined in class in which this method is invoked like:
class A {
private Lazy<FabricClient> _fabricClient => new Lazy<FabricClient>(() => GetDefaultFabricClient());
private FabricClient FabricClient => _fabricClient.Value;
internal A()
{
Console.WriteLine(FabricClient.ToString());
}
private void tempMethod()
{
List<String> listOfStrings = GetStrings();
RunThreads(listOfStrings.Select<string, ThreadStart>(tempString => () =>
{
var x = FabricClient.GetServiceList();
}).ToArray());
}
private FabricClient GetDefaultFabricClient()
{
// Environment is inherited property, I cannot edit it
// And it's defined like
//
// public Environment Environment
// { get { return _context.Environment; }}
//
if (Environment.IsPublicEnvironment)
{
return new FabricClient(Credentials, Endpoint);
}
return new FabricClient();
}
}
Is it possible to ensure that all threads would access same property, same object (as currently each thread is initializing its own FabricClient Lazy object, not reusing previous one being initialized, possibly not making it static)?
Also lazy FabricClient property is being populated before tempMethod execution, but it's not being reused in RunThreads method.