2009-08-06 36 views

Trả lời

45

WebClient không có thuộc tính hết thời gian chờ, tuy nhiên có thể kế thừa từ WebClient để cấp quyền truy cập vào Thời gian chờ trên WebRequest nội bộ được sử dụng:

public class WebClientEx : WebClient 
{ 
    public int Timeout {get; set;} 

    protected override WebRequest GetWebRequest(Uri address) 
    { 
     var request = base.GetWebRequest(address); 
     request.Timeout = Timeout; 
     return request; 
    } 
} 

Cách sử dụng:

var myClient = new WebClientEx(); 
myClient.Timeout = 900000 // Daft timeout period 
myClient.UploadData(myUri, myData); 
+1

Great câu trả lời. FYI Tôi đã sử dụng nó và nó cũng hoạt động với 'WebClient.UploadValues ​​()' – AlbatrossCafe

1

vì vậy, đối với những người mã trong VB ...

Public Class WebClientExtended 
    Inherits WebClient 
    Public Property Timeout() As Integer 
     Get 
      Return m_Timeout 
     End Get 
     Set(value As Integer) 
      m_Timeout = value 
     End Set 
    End Property 
    Private m_Timeout As Integer 

    Protected Overrides Function GetWebRequest(address As Uri) As WebRequest 
     Dim request = MyBase.GetWebRequest(address) 
     request.Timeout = Timeout 
     Return request 
    End Function 
End Class 

Function (URL ByVal As String, ByVal filepath As String, ByVal FileName As String) UploadFile

'Call API to Upload File 
    Dim myWebClient As New WebClientExtended 
    myWebClient.Timeout = 10 * 60 * 1000 
    Dim responseArray As Byte() 
    Dim responseString As String = "" 

    Try 
     responseArray = myWebClient.UploadFile(URL, FilePath + "/" + FileName) 
     responseString = System.Text.Encoding.ASCII.GetString(responseArray) 
    Catch ex As Exception 
     responseString = "Error: " + ex.Message 
    End Try 

    Return responseString 

End Function 

(Đây chỉ là bài viết thứ hai của tôi)

Các vấn đề liên quan