3

When I load a page in my app I fire off a series of WebClient.DownloadStringAsync requests. These go out and perform json api calls. I have noticed that if the user presses the back button before the app hits my WebClient_StringCompleted the task is still completed and I would rather it not to. Is there a way to stop all async tasks using the OnBackKeyPress override?

UPDATE:

I ended up blending both of the below answers. Here is my code I settled on:

 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 is a class variable of type CancellationTokenSource

I can then fire off in my OnBackKeyPress override;

ct.Cancel();

This will cancel all WebClient's using the CancelAsync() method in the WebClient.

4

2 回答 2

2

根据WebClient.DownloadStringAsync Method (Uri)的文档:

您可以使用CancelAsync方法取消尚未完成的异步操作。

你试过了吗?

您可以使用HttpClient 类并使用GetAsync 方法的重载之一,该方法采用CancellationToken并使用它来取消所有挂起的操作。

您可以在HTTP 客户端库 NuGet 包 (Microsoft.Net.Http)上从Windows Phone获取HttpClient 类

于 2013-05-12T19:26:08.020 回答
1

最近,我看了一些关于 CancellationToken 和 Progress Reporting 的不错的教程,但适用于 Windows 8 应用程序。在这里查看(第二个视频是使用 CancellationToken 来停止异步工作),我认为它可能会对您有所帮助。

于 2013-05-11T01:44:57.827 回答