User_MK User_MK - 20 days ago 5
C# Question

Functionality of Async/Await, does it affect timing?

I'll be referring to this answer by Stephen Cleary from another post.

I'm trying to implement something similar, but I am fairly new to C#.

My question is: The

await
is applied to
ReadAsync
, and if
ReadAsync
has not completed then it returns from the
ReadAllFileAsync
method to
Main
, and then, what happens? Does
Main
continues running?

The reason for my question is that I want to know how the stopwatch elapsed time would not be affected by this.
If the important work is reading the file (since we're timing it), and there's no UI at risk of being blocked, why use
async
/
await
?

Answer

I'll be referring to this answer by Stephen Cleary from another post.

OK, but be sure to take note of Mike Marynowski's comment. It's important.

The await is applied to ReadAsync, and if ReadAsync has not completed then it returns from the ReadAllFileAsync method to Main, and then, what happens? Does Main continues running?

Yes. Main continues executing, and the very next thing it does is call Wait on the task returned from ReadAllFileAsync, which blocks the current thread until the method completes. Blocking on a task like this is generally a bad idea, but must be done in the Main method of Console applications to prevent the application from exiting.

Normally, when you are timing an asynchronous method, you would want to start the timer immediately before invoking the method, and stop the timer after the returned task has completed. This is usually done by stopping the timer after awaiting the task, but in that example it's done by stopping the timer after Waiting the task.