Windows Phone 8.1 Runtime HttpClient async,结果相同

本文关键字:结果 async HttpClient Phone Runtime Windows | 更新日期: 2023-09-27 18:05:33

我正在使用Windows Phone运行时API。我声明了一个计时器,它每2秒在Listen方法中进行异步http连接。

Timer t = new Timer(Listen, null, 0, 2000);

Listen法:

private async void Listen(object state)
{
    string url = "http://www.mywebpage.com?data=my_data";
    string responseBodyAsText = null;
    var response = new HttpResponseMessage();
    var httpClient = new HttpClient();
    try
    {
        response = await httpClient.GetAsync(new Uri(url));
        responseBodyAsText = await response.Content.ReadAsStringAsync();
    }
    catch
    {
        //...
    }
    Debug.WriteLine(responseBodyAsText);
    httpClient.Dispose();
}

我的问题是,responseBodyAsText包含始终相同的数据(给定相同的uri),而不是我期望根据我的外部行为不同的数据(修改网页或不同的结果与相同的uri)。HttpClient在应用的整个生命周期内记忆内容吗?我该如何解决这个问题?

Windows Phone 8.1 Runtime HttpClient async,结果相同

HttpClient默认开启缓存。您可以通过传递HttpBaseProtocolFilter:

来关闭它。
var filter = new HttpBaseProtocolFilter
{
    CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent,
    CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
}
边注:你也可以,而不是Timer,使用Task.Delay来实现定时器行为(它内部使用一个):
private async Task ListenAsync()
{
    while (someCondition)
    {
        string url = "http://www.mywebpage.com?data=my_data";
        string responseBodyAsText = null;
        var response = new HttpResponseMessage();
        using (var httpClient = new HttpClient())
        {
            try
            {
                response = await httpClient.GetAsync(new Uri(url));
                responseBodyAsText = await response.Content.ReadAsStringAsync();
             }
            catch
            {
                //...
            }
            Debug.WriteLine(responseBodyAsText);
            await Task.Delay(2000);
        }
}