从方法外部取消GetAsync请求

Rov*_*dov 2 c# wpf async-await

我有大量的异步请求.在某些时候,当应用程序停用(暂停)时,我需要取消所有请求.我正在寻找一种取消异步方法之外的请求的解决方案.有人能指出我正确的方向吗?

这是一大堆代码.

异步方法:

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();
        }
        ...
Run Code Online (Sandbox Code Playgroud)

调用方法:

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

停用事件:

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    //Here i need to stop all requests.
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ary 10

您只需创建一个(共享)实例CancellationTokenSource:

private CancellationTokenSource _cts = new CancellationTokenSource();
Run Code Online (Sandbox Code Playgroud)

然后,将所有异步操作绑定到该标记:

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

最后,在适当的时候取消CTS:

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
  _cts.Cancel();
  _cts = new CancellationTokenSource();
}
Run Code Online (Sandbox Code Playgroud)