Domanda

Imagine that I have a button click event handler like:

public async void btn_Click(...)
{
    await longRunningOperationAsync();
    x += 2;
}

public async void btn2_Click(...)
{
   await longRunningOperationAsync();
   x += 3;
}

If the user clicks btn and immediately clicks btn2 just after, does it cause data races? The statements after await will be executed concurrently (e.g. preemption) in single thread (UI), right?

However, I have read this in that website: "all of your code is running in the UI thread, so you don't have the issues with UI updates. In addition, none of your code is running concurrently, which eliminates the data integrity issues (deadlocks, race conditions) typically associated with concurrency." http://www.techrepublic.com/blog/software-engineer/why-net-developers-should-check-out-the-await-system/

I basically did not understand what happens.

È stato utile?

Soluzione

In this case, there is no data race, because await will capture the UI context and resume the async methods in that context. You may find my async introduction post helpful.

The order in which they resume is not guaranteed, but they are not concurrent in the sense of preemption. In a UI context, you can think of the async method as split into several chunks (at each await). Each chunk will execute one at a time and cannot be preempted by another chunk.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top