2013-03-26 72 views
1

即使我正在創建WebClient的新實例,並遵循標準過程以確保WebClient已被GC刪除,這甚至都不應該考慮:webclient從我之前檢索到的服務器檢索內容,並且只重新啓動應用程序它是否會允許從我的服務器獲取新內容。內容是一個簡單的文本文件字符串,沒有花哨的緩存,因爲它在WinRT上工作得很好。WebClient和任務不檢索新內容,但新內容可用?

這是一個謎,因爲我試圖做一個聊天框;我需要刷新以獲取新內容,但WebClient首次返回它檢索到的內容。

我的代碼:

public async Task<string> RetrieveDocURL(Uri uri) 
    { 

     return await DownloadStringTask(new WebClient(), uri); 
    } 

    /* 
    public async Task<byte[]> RetrieveImageURL(string url) 
    { 
     return await _webClient.GetByteArrayAsync(url); 
    } 
    * */ 

    private Task<string> DownloadStringTask(WebClient client, Uri uri) 
    { 
     var tcs = new TaskCompletionSource<string>(); 

     client.DownloadStringCompleted += (o, e) => 
      { 
       if (e.Error != null) 
        tcs.SetException(e.Error); 
       else 
        tcs.SetResult(e.Result); 
      }; 

     client.DownloadStringAsync(uri); 

     return tcs.Task; 
    } 
+2

WebClient的緩存策略非常具有侵略性。如果每次查詢相同的URL,則應該考慮在最後添加一個隨機參數。類似於「」http://www.yourserver.com/yourService/?nocache=「+ DateTime.UtcNow.Ticks' – 2013-03-26 08:08:00

+0

謝謝!這是解決方案!將此添加到答案中。 – 2013-03-26 10:52:04

回答

2

Web客戶端的緩存策略是非常積極的。如果每次查詢相同的URL,則應該考慮在最後添加一個隨機參數。例如:

"http://www.yourserver.com/yourService/?nocache=" + DateTime.UtcNow.Ticks 
+0

這幫了我很多時間。好戲 – 2013-03-26 22:57:35