Search code examples
vb.netasynchronousparallel-processingasync-awaitdeadlock

DownloadStringTaskAsync Result DeadLock when using UI


This is my code:

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

When this function runs without UI it runs fine, but when i try to run it via UI it stucks in webContent.Result.contains(o)

How can i a make it work using UI?


Solution

  • You are deadlocking on the UI thread because Task.Result is blocking. You need to use async-await instead.

    Change your function to return Task(Of String), add the Async keyword and the Async suffix to the function name (which is the naming convention):

    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