Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cancel GetAsync request from outside of method

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.
}
like image 944
Rovshan Mamedov Avatar asked Feb 14 '14 18:02

Rovshan Mamedov


People also ask

Should all async methods have a cancellation token?

Description: Asynchronous methods should take a CancellationToken. Sometimes, async methods are not written with cooperative cancellation in mind. Either because a developer is not aware of the pattern or because they consider it unnecessary in a specific case.

How do I cancel async tasks?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.

What does HttpClient GetAsync return?

The HTTP request is sent out, and HttpClient. GetAsync returns an uncompleted Task .

How do cancellation tokens work C#?

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property.


1 Answers

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();
}
like image 86
Stephen Cleary Avatar answered Oct 02 '22 13:10

Stephen Cleary