表明网络行为的最佳方式

时间:2015-05-05 20:58:30

标签: c# windows-runtime windows-store-apps windows-phone-8.1 async-await

我正在开发新闻客户端,并且在下载数据时会出现问题。 我有像folows这样的方法:

    public async Task LoadAsync()
    {
        var src = CurrentSource;

        if (src != null && !src.IsLoading)
        {
            src.IsLoading = true;
            var uri = new Uri(GetFeedUri);
            try
            {
                var items = await _networkService.GetAsync<List<NewsItem>>(uri);
                _dispatcherService.SafeAction(() => src.Items.AddRange(items));
                await SaveSources();

                src.LastUpdate = DateTime.Now;
            }
            catch (Exception)
            {
                _loggerService.LogMessage(NoInternetConnection, LoggerType.Error);
            }
            src.IsLoading = false;
        }
    }

GetAsync的实现:

    public async Task<T> GetAsync<T>(Uri uri)
    {
        using (var http = WrappedHttpClient())
        {
            try
            {
                var cancel = new CancellationTokenSource(10000);
                var response = await http.GetAsync(uri, cancel.Token);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    _eventAggregator.GetEvent<NetworkError>().Publish(true);
                    throw new FileNotFoundException(string.Format("No Internet connection. Code: {0}.", response.StatusCode));
                }
                var json = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<T>(json);
                _eventAggregator.GetEvent<NetworkError>().Publish(false);
                return result;
            }
            catch
            {
                _eventAggregator.GetEvent<NetworkError>().Publish(true);
                throw new FileNotFoundException("No Internet connection.");
            }
        }
    }

WrappedHttpClient只是将标头添加到HttpClient。

IsLoading属性绑定到视图上的ProgressBar以指示下载并影响命令(刷新,加载更多)。

大部分时间这段代码效果很好,但有时src.IsLoading不会切换为false,我不知道为什么。还有其他方法可以解决这个问题吗?或者我不考虑一些观点?请帮忙。

0 个答案:

没有答案