【发布时间】:2013-05-14 09:46:25
【问题描述】:
当我在我的应用程序中加载页面时,我会触发一系列 WebClient.DownloadStringAsync 请求。这些出去并执行 json api 调用。我注意到,如果用户在应用程序点击我的WebClient_StringCompleted 之前按下后退按钮,任务仍然完成,我不希望它这样做。有没有办法使用 OnBackKeyPress 覆盖来停止所有异步任务?
更新:
我最终混合了以下两个答案。这是我确定的代码:
WebClient VideoDetails = new WebClient();
id = parameter;
VideoDetails.DownloadStringCompleted += new DownloadStringCompletedEventHandler(VideoDetails_StringCompleted);
if (!cts.Token.IsCancellationRequested)
{
using (CancellationTokenRegistration ctr = cts.Token.Register(() => VideoDetails.CancelAsync()))
{
VideoDetails.DownloadStringAsync(new Uri("http://www.url.com/api/get_video_detail?id=" + VideoID));
}
}
cts 是 CancellationTokenSource 类型的类变量
然后我可以在 OnBackKeyPress 覆盖中启动;
ct.Cancel();
这将使用 WebClient 中的 CancelAsync() 方法取消所有 WebClient。
【问题讨论】:
标签: c# windows-phone-7 async-await