简体   繁体   中英

async function - Task Factory

I was trying to wrap my "GetNonEmptyString" function in a Task so i can await it in an async method. The following code returns the correct string, but why is none of the Task.Delay statement executed?

Public Async Function GetDataAsync() As Task(Of String)
    Dim result = Await GetStringAsync()
    Return result
End Function

Public Function GetStringAsync() As Task(Of String)
    Return Task(Of String).Factory.StartNew(Function()
                                                      Task.Delay(100000)
                                                      Return GetNonEmptyString()
                                                  End Function)
End Function

Private Function GetNonEmptyString() As String
    Task.Delay(100000)
    Return "notEmpty"
End Function

Task.Delay is not the equivalent of Thread.Sleep .

Task.Delay returns a Task , which will complete after a delay. In order to actually wait for the task to complete you have to Await the returned task, call its .Result property or the .Wait() method or use a .ContinueWith continuation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM