我正在编写一个简单的方法来验证网页 url 是否真实并返回 True 或 False。
在 .NET 4.5 中使用新的异步等待函数现在看起来非常简单,但是如何为异步设置超时?
''' <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