Reputation: 15
Can anyone explains me why Console.WriteLine(t.Result)
line "blocks" next line "I am done"
? From my understanding if there would be t.Wait()
as shown in code this would be understable to me but in this case it seems t.Results
acts as await itself. To me when line Dim urlContents As String = Await getStringTask
is reached it should call back (because of await) to Main function and proceed directly to line Console.WriteLine("I am done")
, unless t.Wait()
would be uncommented. What am i missing?
Sub Main()
Dim t = Task.Run(Function()
Return AccessTheWebAsync()
End Function)
't.Wait()
Console.WriteLine(t.Result)
Console.WriteLine("I am done")
Console.ReadLine()
End Sub
Async Function AccessTheWebAsync() As Task(Of Integer)
Dim getStringTask As Task(Of Integer) = Task.Run(Async Function()
Await Task.Delay(6000)
Return 999999
End Function)
DoIndependentWork()
Dim urlContents As String = Await getStringTask
Return urlContents.Length
End Function
Sub DoIndependentWork()
Console.WriteLine("DoIndependentWork...")
End Sub
Confirmed that: t.Result = t.Wait()
Upvotes: 0
Views: 41
Reputation: 106920
The .Result
needs to block otherwise it won't know what the result was. It even says so in the documentation:
Accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.
Remember - async/await won't change the order of your statements. If there are two Console.WriteLine()
after one another, then that's the order in which they will be executed.
The beauty of async/await comes when you have several Task
s that can run in parallel - then you can wait on them all at the same time. Or, if you have more stuff to do before you need the .Result
, you can do that first and ask for the Result at the end (so that the task is running in parallel to your other code).
Upvotes: 1