'Do I need to serialize access to class members when all methods are async
I have a rather elementary question. I have converted code to be fully async from end to end. In the past, I have worked with Parallel.ForEach() and use lock(synLock){} to serialize access to class variables. In the code below I am using a normal foreach loop and during each iteration my plan was to buildup _Context for various functions to access and modify during the processing. So my question is -> Would _Context be considered thread safe in a way that I would not have to maintain locks for updates?
protected ServiceWorkContext _Context = new ServiceWorkContext();
protected async Task PerformServiceWork()
{
var orderedProcessingConfigItems = await GetConfiguirationsForProcessingAsync((int)ReportDataGroupEnum.ReportData);
foreach (var config in orderedProcessingConfigItems)
{
var databases = await GetDatabasesAsync();
_Context.ClientDatabase = databases.Where(p => p.ClientDatabaseID == config.ClientDatabaseID).FirstOrDefault();
_Context.LogBatchID = Guid.NewGuid().ToString();
await ProcessOneAsync(); // Is _Context safe to use here
await ProcessTwoAsync(); // and here
await ProcessThreeAsync(); // and here
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
