Benjamin E.
Benjamin E.

Reputation: 5162

Thread-safety of bool flag crossing an async boundary

Can the following case be assumed de facto thread-safe? The bool flag always starts at false and only goes one way to true or stays as is. I know it's actually not thread-safe, but is it possible to really break somehow?

In this case the async execution is even strictly ordered and never parallel.

bool cancelled = false;

await MyAsyncJob.Process(() =>
{
    if (timeout)
    {
        cancelled = true;
    }
});

if (cancelled)
{
    DoSomething();
}

Upvotes: 1

Views: 291

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456607

Can the following case be assumed de facto thread-safe? The bool flag...

It's not clear which flag you're referring to.

In your code, the cancelled flag will work as you expect, because it is checked after the method that sets it is awaited. The code running after the await will see all side-effects caused by the awaited method.

However, timeout does not look thread-safe at all. The awaited code checks timeout but is (probably) not awaiting whatever code sets timeout.

You could go through the trouble of using locks and whatnot, or you can use the CancellationTokenSource, CancellationToken, and OperationCanceledException provided by the .NET framework for exactly this scenario:

try
{
  await MyAsyncJob.Process(() =>
  {
    cancellationToken.ThrowIfCancellationRequested();
  });
}
catch (OperationCanceledException)
{
  DoSomething();
}

By following the standard pattern, other developers will be able to understand your code more quickly. And you won't have to worry about thread safety at all; the provided framework types take care of it.

Upvotes: 1

Related Questions