Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add cancellation token to an async task with progress

I am using below code to do a time consuming operation in a WPF page async way along with progress reporting to the 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..");    
        }  
    }

Now i would like to add an extra option of cancel this async operation in the middle .For doing so i found that i have to add below options

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

But how can i pass this tokenSource to my DoProcessing call and how can i handle cancellation inside DoProcessing

like image 811
Sebastian Avatar asked Apr 11 '18 07:04

Sebastian


1 Answers

You actually don't need to pass the CancellationTokenSource to DoProcessing, but just the CancellationToken.

In order to handle the cancellation you could do something like this:

    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..");    
        }  
    }

In this case you'll need to create the cancellation token source already in btnStart_Click. In case it wasn't clear, you'd need to do like this:

    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));
    }
like image 160
papafe Avatar answered Oct 20 '22 08:10

papafe