2013-02-18 99 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();