嗨,我需要帮助来中止在awiat异步下运行的任务 [英] Hi , I need help to abort a task running under awiat async

查看:104
本文介绍了嗨,我需要帮助来中止在awiat异步下运行的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在等待异步中的WPF用户控件中点击按钮时调用某个任务。我的要求是点击取消取消该运行任务。但是我无法取消它。

I am calling certain task on button click in WPF user control inside await async. My requirement is to cancel that running task on click of cancel. but I am not able to cancel it.

private async void BtnAddDriver_Click(object sender, RoutedEventArgs e)
       {
           try
           {
            await Task.Factory.StartNew(() =>
             {
                 //Fire Do Action in protect to get the driver details after adding the driver in protect
              });

           }
           catch (Exception ex)
           {
           }
           finally
           {
           }
       }





我的尝试:



我试图添加Cancelation标记,然后使用Cancel方法。但无法取消任务。请帮助。



What I have tried:

I tried to add Cancelation token and then use Cancel method. But unable to cancel the task. Please help.

推荐答案

您可以使用接受CancellationToken的TaskFactory.StartNew变体。 MSDN附带一个工作示例:



TaskFactory.StartNew方法(Action,CancellationToken)(System.Threading.Tasks) [ ^ ]
You could use the variant of TaskFactory.StartNew that accepts a CancellationToken. MSDN comes with a working example:

TaskFactory.StartNew Method (Action, CancellationToken) (System.Threading.Tasks)[^]


我的解决方案是: <无论是async-await还是常规同步按钮点击事件处理程序,C#.NET任务取消机制都能正常工作;



2.请确保您在C#代码中使用CancellationTokenSource对象;





3 。如果在生成的异步任务中的每个驱动程序安装阶段之前取消了CancellationTokenSource.IsCancellationRequested属性值,请确保执行检查;



4。请确保您已为c实现了单独的处理程序ancelation按钮单击并调用CancellationTokenSource.Cancel()方法;





以下是:(例如下面的代码实现了一个具有两个按钮的System.Windows.Form基于Windows的应用程序。第一个按钮通常会启动添加驱动程序任务。在这种情况下,它会生成一个在ethernal循环中重复显示消息框的任务,模拟驱动程序安装工作。要生成任务,只需单击添加驱动程序...按钮即可生成任务。要取消所谓的驱动程序安装,您必须切换取消任务按钮,将不再显示消息框,表明特定任务已被取消:





My solution is:

1. The C#.NET tasks cancelation mechanism will work regardless of whether it is an async-await or regular synchronous button click event handler;

2. Please make sure that you are using CancellationTokenSource object in your C# code;


3. Please make sure that you are performing a check if CancellationTokenSource.IsCancellationRequested property value is "true" prior to each driver installation phase within the asynchronous task spawned;

4. Please make sure that you've implemented a separate handler for cancelation button click and invoke CancellationTokenSource.Cancel() method;


Here's how: (e.g. the following code below implements a System.Windows.Form windows-based application having two buttons. The first button normally launches adding driver task. In this case it spawns a task that displays a message box repeatedly in the ethernal loop, simulation the driver installation work. To spawn the task all you need is to click on Add Driver... button. To cancel the so-called "driver installation", you have to toggle cancel task button and the message boxes will no longer be displayed indicating that the specific task has been cancelled:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        static public CancellationTokenSource 
            tokenAddDriverSource = new CancellationTokenSource();
        public Form1()
        {
            InitializeComponent();
            
        }
        private async void BtnAddDriver_Click(object sender, EventArgs e)
        {
            try {
                try
                {
                    await Task.Factory.StartNew(() =>
                    {
                        bool isCanceled = false;
                        while (isCanceled == false)
                        {
                            // Adding driver Phase #1
                            if (tokenAddDriverSource.IsCancellationRequested)
                                isCanceled = true;

                            MessageBox.Show("Fire Do Action in protect to get the driver details after adding the driver in protect");

                            // Adding driver Phase #2
                            if (tokenAddDriverSource.IsCancellationRequested)
                                isCanceled = true;

                            // ....
                            // Adding driver Phase #N
                            if (tokenAddDriverSource.IsCancellationRequested)
                                isCanceled = true;
                        }
                    }, tokenAddDriverSource.Token);
                }
                catch (Exception ex)
                {
                }
                finally
                {
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
        }
        private void CancelTask_Click(object sender, EventArgs e)
        {
            tokenAddDriverSource.Cancel();
        }
    }}





还有一件事:正确执行任务取消,你会更好,将整个驱动程序安装过程分为几个阶段,并在每个阶段安装驱动程序之前执行以下代码:





And, one more thing: to perform task cancelation properly, you would better, divide the entire driver installation process into several phases and execute the following code prior to driver installation each phase:

// ....
// Adding driver Phase #N
if (tokenAddDriverSource.IsCancellationRequested)
    isCanceled = true;





全部:)



That's all :)


这篇关于嗨,我需要帮助来中止在awiat异步下运行的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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