Return a value from a Task

125 views Asked by At

I have 2 code snippets:

// Snippet 1            
int result = await Task.Run(() => LongRunningComputation());
return result;

and

// Snippet 2           
int result = 0;
await Task.Run(() =>
{
    result = LongRunningComputation();
});
return result;

Is Snippet 1 100% equivalent to Snippet 2? Do I have to use locks or Volatile.Read/Volatile.Write when reading/writing result in Snippet 2 to make it 100% equivalent to Snippet 1?

1

There are 1 answers

1
Stephen Cleary On BEST ANSWER

They both do the same thing, if that's what you meant by "100% equivalent". They're obviously not exactly the same.

I would say that snippet 1 is preferable. This is for a number of reasons, but mainly that asynchronous code is by nature functional. You'll find that your method logic is simplified if you return values rather than set shared variables as side effects. There are other lesser advantages to snippet 1 as well, such as avoiding overhead due to lambda variable capture.

You do not have to use locks or volatile in this (simple) example. Task.Run and await take care of issuing memory barriers, so this example will work fine. Of course, if you have other code manipulating result while the delegate is executing, then you would need locks.