从方法外部取消GetAsync请求 [英] cancel GetAsync request from outside of method

查看:109
本文介绍了从方法外部取消GetAsync请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

这是代码段.

异步方法:

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

推荐答案

您只需

You just create a single (shared) instance of CancellationTokenSource:

private CancellationTokenSource _cts = new CancellationTokenSource();

然后,将所有异步操作都绑定到该令牌中:

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

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

Finally, cancel the CTS at the appropriate time:

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

这篇关于从方法外部取消GetAsync请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆