Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Await Timeout

I am writing a simple method that validates a webpage url is real and returns either True or False.

Using the new async await functions in .NET 4.5 this now seems ridiculously easy, but how do I set a timeout for async?

''' <summary>
''' Returns True if a webpage is valid.
''' </summary>
''' <param name="url">Url of the webpage.</param>
Private Async Function VailiateWebpageAsync(url As String) As Task(Of Boolean)       
    Dim httpRequest As HttpWebRequest
    Dim httpResponse As HttpWebResponse

    httpRequest = CType(WebRequest.Create(url), HttpWebRequest)
    httpRequest.Method = "HEAD" 'same as GET but does not return message body in the response

    Try
        httpResponse = CType(Await httpRequest.GetResponseAsync, HttpWebResponse)
    Catch ex As Exception
        httpResponse = Nothing
    End Try

    If Not IsNothing(httpResponse) Then
        If httpResponse.StatusCode = HttpStatusCode.OK Then
            httpResponse.Dispose()
            Return True
        End If
    End If

    If Not IsNothing(httpResponse) Then httpResponse.Dispose()
    Return False
End Function
like image 456
George Filippakos Avatar asked Jul 04 '26 01:07

George Filippakos


2 Answers

Per the author's comment, I gather he wants to be able to timeout ANY async. This is the method I use on .NET 4 on get a 10 second timeout. Syntax will vary slightly on .NET 4.5 because they replaced the static methods on the TaskEx class with the Task class.

        var getUserTask = serviceAgent.GetAuthenticatedUser();
        var completedTask = await TaskEx.WhenAny(getUserTask, TaskEx.Delay(10000));

        if (completedTask != getUserTask)
        {
            Log.Error("Unable to contact MasterDataService to retrieve current user");
            MessageBox.Show("Unable to contact the server to retrieve your user account.  Please try again or contact support.");
            Application.Current.Shutdown();
        }

This code will kick off the GetAuthenticatedUser asynchronous task but will not hold on that line because there is no await there. Instead it moves onto the next line and awaits either the getUserTask or a 10 second delay. Whichever completes first will cause that line's await to return. We can determine whether the timeout occurred by examining the Task returned by TaskEx.WhenAny or by querying getUserTask and looking at its Status

like image 141
Kevin Kalitowski Avatar answered Jul 08 '26 13:07

Kevin Kalitowski


HttpWebRequest has a Timeout property that you can set:

MSDN: HttpWebRequest.Timeout

If the timeout is exceeded, a WebException will be thrown with the Status property set to Timeout which you can then catch and handle.

like image 27
Nick Butler Avatar answered Jul 08 '26 14:07

Nick Butler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!