Asynchronous methods with and without async modifier

What is the difference between the Add1() and Add2() methods? Is there any difference at all? For all I know, the usage (as shown in the UsageTest() method) is the same.

 private async Task<int> Add1(int a, int b) { return await Task.Run( () => { Thread.Sleep(1000); return a + b; }); } private Task<int> Add2(int a, int b) { return Task.Run( () => { Thread.Sleep(1000); return a + b; }); } private async void UsageTest() { int a = await Add1(1, 2); int b = await Add2(1, 3); } 
+4
source share
2 answers

Semantically, they are almost equivalent.

The main difference is that Add1 has additional overhead (for the async state machine).

There is also less difference; Add1 will return to the original context, but Add2 not. This can cause a dead end if the calling code does not use await :

 public void Button1_Click(..) { Add1().Wait(); // deadlocks Add2().Wait(); // does not deadlock } 

I explain this deadlock situation in more detail on my blog and in a recent MSDN article .

+6
source

Add1 will run synchronously until it encounters a wait keyword. In this case, this will have no effect, because the wait keyword is found at the beginning of the method.

To see the effect of this, you can insert the Thread.Sleep () method at the beginning of Add1 and Add2 and notice that the method is marked as aync blocks before it returns.

+1
source

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


All Articles