2013-02-18 102 views
1

我正在開發一個Silverlight應用程序,該應用程序除了其他內容之外還使得Http請求能夠從Web服務器上傳zip文件。每隔n分鐘從網絡服務器上獲取zip文件,這是一個由定時器控制的行爲。Silverlight只發出一個http請求

我試過使用WebClientHttpWebRequest類,結果相同。該請求僅在第一次到達Web服務器。第二,第三,...發送請求併發出響應。但是,請求永遠不會到達Web服務器...

void _timer_Tick(object sender, EventArgs e) 
    { 
     try 
     { 
      HttpWebRequest req = WebRequest.CreateHttp(_serverUrl + "channel.zip"); 
      req.Method = "GET"; 

      req.BeginGetResponse(new AsyncCallback(WebComplete), req); 
     } 
     catch (Exception ex) 
     { 

      throw ex; 
     } 
    } 

    void WebComplete(IAsyncResult a) 
    { 

     HttpWebRequest req = (HttpWebRequest)a.AsyncState; 
     HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(a); 
     Stream stream = res.GetResponseStream(); 

     byte[] content = readFully(stream); 
     unzip(content); 

    } 

是否有某種瀏覽器緩存問題在這裏? 我希望我所做的每一個請求都能夠一路訪問Web服務器。

回答

2

是的,瀏覽器可能會緩存請求。如果要禁用,您可以修改服務器發送一個Cache-Control: no-cache頭,或者可以追加某種唯一標誌的URL的,以防止瀏覽器緩存的要求:

void _timer_Tick(object sender, EventArgs e) 
{ 
    try 
    { 
     HttpWebRequest req = WebRequest.CreateHttp(_serverUrl + "channel.zip?_=" + Environment.TickCount); 
     req.Method = "GET"; 

     req.BeginGetResponse(new AsyncCallback(WebComplete), req); 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
} 
+0

謝謝!這件事情讓我感到很快樂! – 2013-02-19 16:08:56

0

機會是你的計時器凍結,而不是網絡請求。將Debug.WriteLine放入您的計時器事件中,確保它不止一次被調用。

使用計時器進行後臺任務也是一個壞主意。而不是計時器,創建睡眠請求之間的後臺任務是更好的選擇。這種方式甚至太長的服務器請求不會導致調用重疊。

嘗試在東西線:

BackgroundWorker worker = new BackgroundWorker(); 
worker.DoWork+=(s,a)=>{ 
    try{ 
     while (true)// or some meaningful cancellation condition is false 
     { 
      DownloadZipFile(); 
      Sleep(FiveMinutes); 
      // don't update UI directly from this thread 
     } 
    } catch { 
     // show something to the user so they know automatic check died 
    } 
}; 
worker.RunAsync();