2009-08-03 118 views
2

我打電話給服務器api並等待響應。我只能在得到服務器響應後才能繼續。但有些時候服務器響應只有在一段時間後纔會收到,而我的標題欄顯示「Not responding」消息。我該如何解決這個問題。沒有響應顯示在標題欄

我的代碼塊是

private string SubmitDocument(XmlDocument xmlinput, string URL) 
    { 
     try 
     { 
      // get the data from the xml document into a byte stream 
      Byte[] byteinput = System.Text.Encoding.UTF8.GetBytes(xmlinput.OuterXml); 

      // instantiate a web client 
      System.Net.WebClient myWebClient = new System.Net.WebClient(); 
      myWebClient.Headers.Add("Content-Type", "text/xml"); 

      byte[] responseArray = myWebClient.UploadData(URL, byteinput); 


      string responseString = Encoding.ASCII.GetString(responseArray); 


      return responseString; 
     } 
     catch(Exception ex) 
     {     
      return null; 
     } 
    } 

感謝

回答

-1

的Windows顯示應用中絲毫不差,當窗口過程循環(也就是你的主應用程序線程)不處理郵件的未響應的消息。

當您的主應用程序線程忙於某種等待或循環(就像您描述並無法處理Windows消息)時,會發生這種情況。

你有一些選擇,因爲應用程序無法繼續,直到它從服務器獲取的響應,你必須選擇:

  1. 等待服務器上的第二個線程,讓您的應用程序「停止」直到收到響應爲止(並且停止了我的意思是處理用戶界面,但無法做其他任何事情,例如使用進度條和信號量)。
  2. 不時使用Application.DoEvents()。對於這個工作,你需要能夠等待服務器僅一段時間:

while (!initialized) 
{ 
    Application.DoEvents(); 
    initialized = Server.WaitInitialize(1000); 
} 
+1

`DoEvents`很少是這個問題的好答案... – 2009-08-03 10:56:28

8

而不是阻止用戶界面,做好這項工作在後臺線程(也許BackgroundWorker,也許ThreadPool)。由於它聽起來像你想模仿同步,只需禁用的UI控件 - 不要掛錶格。然後在從服務器獲取響應時更新UI。

0

我會建議實現異步回調。這會讓你的應用程序響應。您可以通過webrequest類輕鬆實現異步回調。