加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用进度将取消令牌添加到异步任务

发布时间:2020-12-15 22:50:40 所属栏目:百科 来源:网络整理
导读:我使用下面的代码在 WPF页面异步方式中执行耗时的操作以及向UI报告进度 private void btnStart_Click(object sender,RoutedEventArgs e) { txt_importStatus.Text = ""; var progress = new Progressstring(progress_info = { //show import progress on a t
我使用下面的代码在 WPF页面异步方式中执行耗时的操作以及向UI报告进度

private void btnStart_Click(object sender,RoutedEventArgs e)
    {
        txt_importStatus.Text = "";
        var progress = new Progress<string>(progress_info =>
        {
            //show import progress on a textfield
            txt_importStatus.Text = progress_info + Environment.NewLine + "Please dont close this window while the system processing the excel file contents";              
        });
        // DoProcessing is run on the thread pool.
        await Task.Run(() => DoProcessing(progress));
    }

    public void DoProcessing(IProgress<string> progress)
    {

        //read an excel file and foreach excel file row
        foreach(excelrow row in excelrowlist)
        {
            //do db entry and update UI the progress like 
            progress.Report("Processed x number of records. please wait..");    
        }  
    }

现在我想添加一个额外的选项,在中间取消这个异步操作.为此我发现我必须添加以下选项

CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;    
private void btnCacnel_Click(object sender,RoutedEventArgs e)
{
    tokenSource.Cancel();
}

但是如何将此tokenSource传递给我的DoProcessing调用以及如何在DoProcessing中处理取消

解决方法

实际上,您不需要将CancellationTokenSource传递给DoProcessing,而只需要将CancellationToken传递给DoProcessing.

为了处理取消,您可以执行以下操作:

public void DoProcessing(CancellationToken token,IProgress<string> progress)
    {
        //read an excel file and foreach excel file row
        foreach(excelrow row in excelrowlist)
        {
            if(token.IsCancellationRequested)
                break;

            //do db entry and update UI the progress like 
            progress.Report("Processed x number of records. please wait..");    
        }  
    }

在这种情况下,您需要在btnStart_Click中创建取消令牌源.如果不清楚,你需要这样做:

CancellationTokenSource tokenSource;

    private void btnStart_Click(object sender,RoutedEventArgs e)
    {
        txt_importStatus.Text = "";
        var progress = new Progress<string>(progress_info =>
        {
            //show import progress on a textfield
            txt_importStatus.Text = progress_info + Environment.NewLine + "Please dont close this window while the system processing the excel file contents";              
        });
        // DoProcessing is run on the thread pool.
        tokenSource = new CancellationTokenSource();
        var token = tokenSource.Token;
        await Task.Run(() => DoProcessing(token,progress));
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读