使用 UI 时 DownloadStringTaskAsync 结果死锁
DownloadStringTaskAsync Result DeadLock when using UI
这是我的代码:
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 使其工作?
您正在 UI 线程上死锁,因为 Task.Result
正在阻塞。您需要改用 async-await。
将您的函数更改为 return 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
这是我的代码:
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 使其工作?
您正在 UI 线程上死锁,因为 Task.Result
正在阻塞。您需要改用 async-await。
将您的函数更改为 return 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