2017-07-15 111 views
0

嘗試後的數據發送到我的PHP服務器時,我得到一個錯誤。 這個調用在我的程序中的一個地方工作,但不是第二個。WebClient的UploadValues連接收出意外

我的PHP代碼只是一個簡單的回聲,我測試過的網頁,並運行良好。

拋出異常:在System.dll中「System.Net.WebException」的 基礎連接已關閉:連接被關閉 意外。

public static class NetworkDeploy 
{ 
    public delegate void CallBack(string response); 

    public static void SendPacket(string url, CallBack callback) 
    { 
     SynchronizationContext callersCtx = SynchronizationContext.Current; 
     Thread thread = new Thread(() => 
     { 
      using (var client = new WebClient()) 
      { 
       NameValueCollection values = new NameValueCollection(); 
       values["test"] = "test"; 
       // exception occurs at the next line 
       byte[] uploadResponse = client.UploadValues(url, "POST", values); 
       string response = Encoding.UTF8.GetString(uploadResponse); 
       if (callback != null) callersCtx.Post(new SendOrPostCallback((_) => callback.Invoke(response)), null); 
      } 
     }); 
     thread.SetApartmentState(ApartmentState.STA); 
     thread.Start(); 
     thread.Join(); 
    } 
} 

我試圖把異常行的for循環是這樣的:

byte[] uploadResponse = null; 
for (int i=0; i<10; i++) 
{ 
    try 
    { 
     // exception occurs at the next line 
     uploadResponse = client.UploadValues(url, "POST", values); 
     break; 
    } catch (Exception e) { } 
} 

和PHP代碼只是

<?php 
echo "Success"; 
+0

這部分運行一次或循環?你是否嘗試過HttpClient而不是WebClient。 –

+0

它運行一次,但我已經在循環中嘗試過。我被困在.Net 4.0,不能使用4.5 –

+0

我建議看看使用'HttpClient'已被optomized這些類型的操作。 此外,我可以看到你在哪裏開始線程,但你在哪裏等待線程完成並得到結果? –

回答

0

我懷疑這個問題是來自使用SynchronizationContext.Current以及代理如何被調用回調到主UI線程中。

我寫概念的樣本證據來做到這一點使用一個任務工廠和匿名的與會代表,應該讓你從你的UI線程調用任務,然後處理在UI線程上完成的結果。

我希望這解決了這個問題:

Task<string> SendPacket(string url) 
    { 
     return Task<string>.Factory.StartNew(() => 
     { 
      using (var client = new WebClient()) 
      { 
       NameValueCollection values = new NameValueCollection(); 
       values["test"] = "test"; 
       // exception occurs at the next line 
       byte[] uploadResponse = client.UploadValues(url, "POST", values); 
       return Encoding.UTF8.GetString(uploadResponse); 
      } 
     }); 
    } 

    void Main() 
    { 
     for (int i = 0; i < 5; i++) 
     { 
      SendPacket("http://localhost:8733/api/values").ContinueWith(task => DoSomethingOnCallback(task.Result)); 
     } 
    } 

    void DoSomethingOnCallback(string response) 
    { 
     Console.WriteLine(response); 
    }