从方法外部取消GetAsync请求

时间:2014-02-14 18:06:09

标签: 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();
        }
        ...

调用方法:

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

停用活动:

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

1 个答案:

答案 0 :(得分:10)

你只是create a single (shared) instance of CancellationTokenSource

private CancellationTokenSource _cts = new CancellationTokenSource();

然后,tie all asynchronous operations into that token

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

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

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
  _cts.Cancel();
  _cts = new CancellationTokenSource();
}