What change does the keyword "await" make?

Shervan360 1,641 Reputation points
2025-03-08T21:56:27.31+00:00

Hello,

Without "await" keyword FileStream.ReadAsync return "Task<int>".

With "await" keyword FileStream.ReadAsync return "int".

Could you please why this happened? What happens behind the scenes?

Screenshot 2025-03-08 224240

Screenshot 2025-03-08 224316

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,333 questions
0 comments No comments
{count} votes

Accepted answer
  1. Marcin Policht 38,000 Reputation points MVP
    2025-03-08T22:17:07.88+00:00

    This happens because FileStream.ReadAsync is an asynchronous method that returns a Task<int>, representing a pending operation.

    1. Without await:
      • ReadAsync immediately returns a Task<int>, which acts as a promise for the future completion of the read operation.
      • The calling code receives this Task<int> and can later use .Result, .Wait(), or await to get the actual integer result when the operation completes.
    2. With await:
      • The await keyword unwraps the Task<int> and retrieves the actual integer value when the asynchronous operation completes.
      • The execution of the calling method is paused at await until the Task<int> completes, and then execution resumes with the result of the operation.

    Effectively, await does not make the operation synchronous. Instead, it allows the current method to return control to the caller while waiting for the asynchronous operation to finish. The compiler transforms an async method into a state machine, handling continuations when the awaited Task<int> completes.


    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.