0

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?

Community
  • 1
  • 1
User_MK
  • 63
  • 1
  • 6
  • Can you give a code example? Do you mean what happens when I do something like "await ReadAllFileAsync()"? – EJoshuaS - Stand with Ukraine Nov 18 '16 at 21:37
  • `ReadAllFileAsync` returns a Task. *await* or *Wait()*, it will not complete before `await file.ReadAsync` completes.... So you can think async/await as a *syncronous* code that doesn't block the calling thread.. – L.B Nov 18 '16 at 21:38
  • 1
    "_there's no UI at risk of being blocked_" it doesn't have to be. They are just testing and comparing some methods. – M.kazem Akhgary Nov 18 '16 at 21:47
  • Please include a [mcve] in your question. – CodeCaster Nov 18 '16 at 22:07
  • @L.B Oh I see, he's also using the .Wait() which, if I understand correctly, waits till the task (returned by ReadAllFileAsync) is complete? And this way the stopwatch correctly measures the time for the tasks to complete. – User_MK Nov 18 '16 at 23:10

1 Answers1

0

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.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810