0

I have a case where i have to implement an addition atomically and just to save a statement - i did the below

int result = Interlocked.Add(ref int source, await ComputeAsync(object someObj);

public async Task<int> ComputeAsync(object someObj)
{
  // some operations
  ....
}

Is there anything wrong with the above Interlocked.Add statement. Can we pass an await function which returns an int as param to the add stmt? What are the implications if any ?

Adi
  • 1
  • 4

1 Answers1

0

That code would work fine, as long as you understand that ComputeAsync will be fully completed before Add is invoked. That is, the order of execution is like this:

int value = await ComputeAsync(someObj);
int result = Interlocked.Add(ref int source, value);
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810