5

I have large numbers of async requests. At some point, when application is deactivated (paused) I need cancel all requests. I'm looking for a solution to cancel requests outside of async method. can someone point me in a right direction?

Here is chunks of code.

The async method:

public async void GetDetailsAsync(string url)
{
    if (this.LastDate == null)
    {
        this.IsDetailsLoaded = "visible";
        NotifyPropertyChanged("IsDetailsLoaded");
        Uri uri = new Uri(url);
        HttpClient client = new HttpClient();
        HtmlDocument htmlDocument = new HtmlDocument();
        HtmlNode htmlNode = new HtmlNode(0, htmlDocument, 1);
        MovieData Item = new MovieData();
        string HtmlResult;

        try
        {
            HtmlRequest = await client.GetAsync(uri);
            HtmlResult = await HtmlRequest.Content.ReadAsStringAsync();
        }
        ...

calling method:

for (int i = 0; i < App.ViewModel.Today.Items.Count; i++)
{
    App.ViewModel.Today.Items[i].GetDetailsAsync(App.ViewModel.Today.Items[i].DetailsUrl);
}

deactivate event:

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    //Here i need to stop all requests.
}
Rovshan Mamedov
  • 270
  • 2
  • 12

1 Answers1

14

You just create a single (shared) instance of CancellationTokenSource:

private CancellationTokenSource _cts = new CancellationTokenSource();

Then, tie all asynchronous operations into that token:

public async void GetDetailsAsync(string url)
{
  ...
  HtmlRequest = await client.GetAsync(uri, _cts.Token);
  ...
}

Finally, cancel the CTS at the appropriate time:

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
  _cts.Cancel();
  _cts = new CancellationTokenSource();
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • That worked :) Deactivated method was in different file than async methods so I made a static method CancelAllThreads(); and called it from App.xaml.cs. – Rovshan Mamedov Feb 14 '14 at 20:26