使用UI时,DownloadStringTaskAsync结果DeadLock

时间:2015-07-01 12:29:32

标签: vb.net asynchronous parallel-processing async-await deadlock

这是我的代码:

Dim getUrlContentTask = Task.Factory.StartNew(Function() GetUrlContent(modifiedUrl))
getUrlContentTask.Wait()

'Check #6 - Check if the url has an expired text in it.
CheckIfExpired(getUrlContentTask)

Public Shared Function GetUrlContent(url As String) As task(of String)

    Try

        Dim webClient As New System.Net.WebClient
        Dim webContent = Await webClient.DownloadStringTaskAsync(url)

        Return webContent
End Function

Public Shared Function CheckIfExpired(webContent As Task(Of String) As Boolean

    If util.ExpiredTexts.Any(Function(o) webContent.Result.Contains(o)) = False Then
        Throw New UriFormatException("Url leads to an expired page")
    End If

    Return True
End Function

当这个函数在没有UI的情况下运行时它运行正常,但是当我尝试通过UI运行它时它会卡住 的 webContent.Result.contains(O)

如何使用UI使其工作?

1 个答案:

答案 0 :(得分:1)

您在UI线程上死锁,因为Task.Result正在阻止。你需要使用async-await。

更改函数以返回Task(Of String),将Async关键字和Async后缀添加到函数名称(这是命名约定):

Public Shared Async Function GetUrlContentAsync(url As String) As Task(Of String)
    Try

        Dim webClient As New System.Net.WebClient
        Dim webContent = Await webClient.DownloadStringTaskAsync(url)

        Return webContent
        End Function