1

I'm working on a Silverlight app which among other things makes Http requests in which it uploads a zip file from the web server. The zip file is picked up from the web server every n:th minute, a behavior controlled by a timer.

I've tried using the WebClient and HttpWebRequest classes with the same result. The request only reaches the web server the first time. The second, third, ..., time the request is sent and a response will occur. However, the request never reaches the web server...

    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);

    }

Is there some kind of browser caching issue here? I want every request I make to go all the way to the web server.

4

2 回答 2

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;
    }
}
于 2013-02-18T22:16:27.420 回答
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();
于 2013-02-18T22:18:57.060 回答