How does asynchronous C # 5.0 work?

I'm trying to understand how the new C # 5 asynchrony function works. Suppose I want to create an atomic increment function to increment an integer in a dummy IntStore. Several calls are made for this function in only one thread.

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

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

How could this be rewritten if IntStore.Get is asynchronous (returns a task) to work correctly?

Performance is crucial, is there a solution that avoids blocking?

+3
source share
1 answer

, , , IntStore.Get. , :

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

IncrementKey , IncrementKey. . , IntStore.Get() :

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

, Starting IntStore 10 .

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."

+4

Source: https://habr.com/ru/post/1795016/


All Articles