Les's assume that we have several async methods and these methods share a class to register some results. We don't know these methods' order of execution. This case doesn't share any static content similarly to ExecutionContext
, so AsyncLocal
isn't a solution here. Is it thread-safe to use the context class without any synchronization (locking) mechanisms in this case? Simplified example:
internal static class Program
{
private static async Task Main(string[] args)
{
var context = new Context();
var classA = new ClassA();
var classB = new ClassB();
await Task.WhenAll(classA.DoSomething(context), classB.DoSomething(context));
// report.Generate(context);
Console.WriteLine($"A: {context.VariableSetByClassA}, B: {context.VariableSetByClassB}");
}
}
public class ClassA
{
public Task DoSomething(Context context)
{
context.VariableSetByClassA = 87;
return DoIOBoundOperationA();
}
}
public class ClassB
{
public async Task DoSomething(Context context)
{
var result = await DoIOBoundOperationB();
context.VariableSetByClassB = result.ValueB;
}
}
public class Context
{
public int VariableSetByClassA { get; set; }
public short VariableSetByClassB { get; set; }
}