使用请求超时 (Net.WebClient)

Use request timeout (Net.WebClient)

您可以使用

为请求设置超时吗
Net.WebClient()

我知道可以使用 WebRequest,但是我想使用 WebClient。

编辑:我创建了一个名为 WbClnt 的新 Class,其中包含以下代码:

Imports System.Net
Public Class WbClnt
    Inherits WebClient
    Protected Overrides Function GetWebRequest(ByVal uri As Uri) As WebRequest
        Dim w As WebRequest = MyBase.GetWebRequest(uri)
        w.Timeout = 5000
        Return w
    End Function
End Class

但是,我无法使用 WbClnt.GetWebRequest 从我的主窗体调用此函数,可能是因为它受保护。

根据以上所有评论,这里是我建议的简单实现。

Imports System.Net

Public Class MyPatientlyWebClient
    Inherits WebClient

#Region "Variables"
    Private ReadOnly _timeOut As Integer = 100000
#End Region

#Region "Properties"

    ''' <summary>
    ''' Determine's how to long to wait for request.
    ''' </summary>
    ''' <returns></returns>
    Public ReadOnly Property HowLongToWait
        Get
            Return _timeOut
        End Get
    End Property
#End Region

#Region "Constructors"
    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal timeOut As Integer)
        MyBase.New()
        If timeOut <= 0 Then timeOut = 100000
        _timeOut = timeOut
    End Sub

#End Region

#Region "Overrides"

    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
        w.Timeout = HowLongToWait
        Return w
    End Function

#End Region

End Class

使用

Dim myPaWebClient As New MyPatientlyWebClient(120000)
Dim str As String = myPaWebClient.DownloadString("https://www.google.com")

您可以根据需要设置属性;需要更改 ReadOnly,我只是快速为您准备了一些东西。