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.