Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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
           {
           }
       }


What I have tried:

I tried to add Cancelation token and then use Cancel method. But unable to cancel the task. Please help.
Posted
Updated 28-May-18 1:44am
v2
Comments
[no name] 28-May-18 5:52am    
Where is your code?

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)[^]
 
Share this answer
 
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:


C#
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:

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


That's all :)
 
Share this answer
 
Comments
Member 13348242 29-May-18 6:17am    
Above code will work if I am clicking on button one by one. But how can interrupt the task running after clicking on button for the first time? How can I stop task running in between?
Arthur V. Ratz 29-May-18 6:25am    
You normally can interrupt this task the same way. Message boxes is for demonstration purposes only. Replace the code displaying message boxes I posted with a custom code adding a driver and you'll see that it works. :)
Arthur V. Ratz 29-May-18 6:29am    
Unfortunately, the author of this question has not posted the code that specifically performs a driver addition. Probably, there would be more other recommendations regarding the task cancelation. *BUT* anyway, try to use what I've already advised with your own code and check if it works. On my side, it works well for sure.
Arthur V. Ratz 29-May-18 6:34am    
Specifically, I use while loop to create an endless task with messages boxes pop-ups that is terminated when and only when a task cancelation token is requested. That's why before each driver addition phase I perform a check if the IsCancellationRequested property value is set to "true". If not, the task will continue its execution, otherwise it will terminate (or just "end-up") with particular token requested.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900