2010-11-06 47 views
0

我說的是POST請求,使用:爲什麼我對WebClient對象的第一次請求總是需要15秒?

WebClient wc = new WebClient(); 
String result = wc.UploadString("http://example.com/", "data=hello, world!"); 

編輯:這是現在我的實際代碼:

String result; 
using (WebClient wc = new WebClient()) 
{ 
    result = wc.UploadString("http://" + "pastebin.com/api_public.php", "POST", "paste_code=" + LongDataEscape(Clipboard.GetText())); 
} 

如果你想知道關於LongDataEscape:

public String LongDataEscape(String Str) 
    { 
     String Output = ""; 
     int ByteCount = 32766; 
     if (Str.Length > ByteCount) 
     { 
      for (int i = 0; i < Str.Length; i+= ByteCount) 
      { 
       if (Str.Length - i < ByteCount) 
        Output += Uri.EscapeDataString(Str.Substring(i, Str.Length - i)); 
       else 
        Output += Uri.EscapeDataString(Str.Substring(i, ByteCount)); 
      } 
     } 
     else 
      Output = Uri.EscapeDataString(Str); 
     return Output; 
    } 

我第一次執行上面這段代碼時,總是需要大約15秒(可能是10),不管我們是什麼它是,但跟隨的相同的代碼片斷是即刻。

我在想這可能會有一些設置,但我還沒有發現。

+0

這聽起來像是在等待超時。是否有可能設置了正在嘗試使用的代理設置?我建議使用Process Monitor(http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx)來查看10-15秒內發生了什麼。 – Gabe 2010-11-07 04:19:19

+0

@加貝我沒有做這樣的事情。我只是試過procmon,並沒有在10秒內顯示任何有趣的東西。只是沒有做任何事情... – Codecat 2010-11-07 16:29:47

回答

4

我固定它。

當你創建一個新的WebClient對象(FtpWebRequest)時,你必須將它的「Proxy」屬性設置爲null。例如:

WebClient wc = new WebClient(); 
wc.Proxy = null; 

然後,第一個請求將永遠不會花費很長時間,您將沒有問題。

+0

不錯,你找到了一個解決方案,但我建議你改變代理設置,這樣你就會忽略你的用戶偏好,從不使用代理,即使他們已經指定了。 – 2010-11-09 16:58:37

0

第一次通話通常需要比後續通話時間更長,但是15s太多。

嘗試做如下改變:

using(WebClient wc = new WebClient()) 
{ 
    String result = wc.UploadString("http://example.com/", "data=hello, world!"); 
} 
+0

是的,也許我用15秒思考太多了,但是這種初始通話時間可以減少嗎? – Codecat 2010-11-06 21:18:47

+0

@Angelo Geels,你有沒有嘗試過我提出的改變?我懷疑15秒延遲是由於您沒有正確關閉WebClient。 – 2010-11-06 21:20:42

+0

剛試過,根本沒有減少10/15秒。 – Codecat 2010-11-06 21:24:30

相關問題