Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C# 5.0 async work?

I'm trying to grok how C# 5's new async feature works. Suppose I want to develop an atomic increment function for incrementing an integer in a fictitious IntStore. Multiple calls are made to this function in one thread only.

async void IncrementKey(string key) {
    int i = await IntStore.Get(key);
    IntStore.Set(key, i+1);
}

It seems to me that this function is flawed. Two calls to IncrementKey could get the same number back from IntStore (say 5), and then set it to 6, thus losing one of the increments?

How could this be re-written, if IntStore.Get is asynchronous (returns Task) in order to work correctly?

Performance is critical, is there a solution that avoids locking?

like image 310
Eloff Avatar asked Mar 05 '26 05:03

Eloff


1 Answers

If you are sure you are calling your function from only one thread, then there shouldn't be any problem, because only one call to IntStore.Get could be awaiting at at time. This because:

await IncrementKey("AAA");
await IncrementKey("BBB");

the second IncrementKey won't be executed until the first IncrementKey has finished. The code will be converted to a state machine. If you don't trust it, change the IntStore.Get(key) to:

async Task<int> IntStore(string str) {
    Console.WriteLine("Starting IntStore");
    await TaskEx.Delay(10000);
    return 0;
}

You'll see that the second Starting IntStore will be written 10 seconds after the first.

To quote from here http://blogs.msdn.com/b/ericlippert/archive/2010/10/29/asynchronous-programming-in-c-5-0-part-two-whence-await.aspx The “await” operator ... means “if the task we are awaiting has not yet completed then sign up the rest of this method as the continuation of that task, and then return to your caller immediately; the task will invoke the continuation when it completes.”

like image 100
xanatos Avatar answered Mar 07 '26 23:03

xanatos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!