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
and Test
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.
Let's break down what Copy
method is doing and we answer the
question whether we really need it to be async
?
Copy
method simply delegates the call to Task.Run
which returns a task that eventually reaches completion on File.Copy
's completion. So the intent is clear here we need a task which notifies File.Copy
completion. This method does all what you need, no need for it to be async
to work as expected.
So, When do you need async
?
You need async when you need to execute some code upon earlier task's completion(Continuation).
Example:
public async Task Test()
{
await Copy("test", "test2");
DoPostCopied(whatever);
await DoPostCopied2();//Etc
}
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…