I'm learning TAP, and I'm wondering what feature of .NET allows the result
in this method to be implicitly cast into or interpreted as a Task(Of String)
:
Public Async Function CheckHostInstructionAsync() As Task(Of String)
Dim result As String
result = Await pipeReader.ReadLineAsync() 'pipeReader is a System.IO.StreamReader
If (result.Equals("exit", StringComparison.InvariantCultureIgnoreCase)) Then terminate = True
Return result
End Function
First, if Await pipeReader.ReadLineAsync()
"returns" a Task(Of String)
, why can I assign it to result
, which is declared as a String?
Second, why can I say Return result
though the return type is Task(Of String)
.
The feature is TAP itself (Task-based Asynchronous Pattern) or async-await
as it's mostly called. The async
keyword tells the compiler to generate a state machine and so you are able to use await
. It also generates a Task
(with the result value, if there is one) or any exception that may arise while the method is running.
In your case pipeReader.ReadLineAsync()
returns a Task(Of String)
and not simply String
. Await
is what enables you to "extract" the actual result out of that task when it's completed.
And when you return result
yourself, the compiler knows to generate a Task(Of String)
that when awaited results in a String
(or an exception, if there was one)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments