I'm trying to get a good grasp of async/await and I want to clear some of the confusion. Can someone please explain what would be the difference in terms of execution for the following:
// version 1
public Task Copy(string source, string destination) {
return Task.Run(() => File.Copy(source, destination));
}
public async Task Test() {
await Copy("test", "test2");
// do other stuff
}
And:
// version 2
public async Task Copy(string source, string destination) {
await Task.Run(() => File.Copy(source, destination));
}
public async Task Test() {
await Copy("test", "test2");
// ...
}
Are they resulting in the same code and why would I write one over the other ?
First of let me start with the point that both codes are not same.
Your version1 code will create only one "State machine" as it contains await in
Test
method only.Your version2 code will create two "state machines" for
Copy
andTest
method which adds some overhead.Why do we use
async
methods? Simple just to make our code readable, elegant while dealing with "Asynchronous Tasks". It makes our code better avoiding callbacks and continuations etc.Copy
method simply delegates the call toTask.Run
which returns a task that eventually reaches completion onFile.Copy
's completion. So the intent is clear here we need a task which notifiesFile.Copy
completion. This method does all what you need, no need for it to beasync
to work as expected.You need async when you need to execute some code upon earlier task's completion(Continuation).
Example:
You can verify this difference between
async
and non async method just by decompiling both versions. It is too long and won't be readable so I skipped posting it here.Conclusion: Use
async
only when required. In this case version1 is better and you should prefer it over version2.