0

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; }
}
rgb
  • 1,750
  • 1
  • 20
  • 35
  • 1
    In your case yes, because you your methods will run synchronously. In a more general sense, no; you would need to consider race conditions if you allow asynchronous methods to run in parallel i.e. invoke the second without awaiting the first. – Johnathan Barclay Dec 08 '21 at 10:25
  • 3
    Why are you in this situation, what is the use case here? There many standard out of the box solutions that can achieve concurrency, deal with shared resources, serialised access if needed and more. However at the moment we have nothing to work with. Can you perhaps explain the actual problem domain and constraints you are working with ? – TheGeneral Dec 08 '21 at 10:33
  • I assume [this](https://stackoverflow.com/a/1151909/2501279) can answer your question. – Guru Stron Dec 08 '21 at 11:03
  • @TheGeneral There is a piece of functionality that gets the results from other microservices. Fetching the data is realized in separate async methods which are running in parallel (I've corrected the example). I have to collect parameters from the execution of these methods and send them to another service to generate the report. – rgb Dec 08 '21 at 11:06
  • Probably it's safe because there is no dependency between those variables: https://stackoverflow.com/a/41365581/1281652 – rgb Dec 08 '21 at 11:37
  • 1
    Somewhat related: [Updating different properties of same object in Parallel.Invoke is thread-safe?](https://stackoverflow.com/questions/69140421/updating-different-properties-of-same-object-in-parallel-invoke-is-thread-safe) – Theodor Zoulias Dec 08 '21 at 12:33

0 Answers0