2014-12-23 19 views
0

我正在使用webclient.downloadfileasync下载许多文件。 我已将最大连接设置为10,因此只能同时下载10个文件。 有时文件从其他地方丢失。当发生这种情况时,DownloadFileAsync只是等待丢失的文件被下载(我不知道多久)。 我想设置一个时间限制,所以如果文件下载没有进行超过30秒的 ,它应该被取消,因此它可以继续下载其他文件。如果下载未进行30秒,则中止DownloadFileAsync

我该怎么办?

 Dim wc As WebClient = New WebClient 

         wc.DownloadFileAsync(Ur1, localFL) 
AddHandler wc.DownloadProgressChanged, Sub(sender As Object, e As DownloadProgressChangedEventArgs) 

我不知道此后。我想我应该为每个downloadfileasync和wc.abort()设置一个30秒计时器,如果DLprogresschanged在30秒内为假,但我不知道如何做到这一点。请帮帮我。从GlennG这里

回答

1

答:How to change the timeout on a .NET WebClient object

有了这个类,你可以设置连接超时。您需要为DownloadFileCompleted事件添加一个AsyncCompletedEventHandler,并处理结果。

Public Class WebClient 
Inherits System.Net.WebClient 

Private _TimeoutMS As Integer = 10000 

Public Sub New() 
    MyBase.New() 
    'MyBase.Encoding = System.Text.Encoding.UTF8 
End Sub 
Public Sub New(ByVal TimeoutMS As Integer) 
    MyBase.New() 
    _TimeoutMS = TimeoutMS 
    'MyBase.Encoding = System.Text.Encoding.UTF8 
End Sub 
''' <summary> 
''' Set the web call timeout in Milliseconds 
''' </summary> 
''' <value></value> 
Public WriteOnly Property setTimeout() As Integer 
    Set(ByVal value As Integer) 
     _TimeoutMS = value 
    End Set 
End Property 

Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest 
    Dim w As System.Net.HttpWebRequest = CType(MyBase.GetWebRequest(address), HttpWebRequest) 
    If _TimeoutMS <> 0 Then 
     w.Timeout = _TimeoutMS 
    End If 
    Return w 
End Function 

End Class