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.
}
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.
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.
The HTTP request is sent out, and HttpClient. GetAsync returns an uncompleted Task .
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With