cancel GetAsync request from outside of method

async-await, c#, wpf

Solution

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();
}

Problem

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. } ```

Original source

Related problems