Add undo token to async task with progress

I use the code below to perform a multi-user operation in asynchronous mode of a WPF page along with progress reports in the user interface

    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 the additional ability to cancel this asynchronous operation in the middle. For this, I found that I need 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 Source token to my DoProcessing call and how can I handle the cancellation inside DoProcessing

+4
source share
1 answer

You do not need to pass CancellationTokenSourcein DoProcessing, but simply CancellationToken.

To handle cancellation, you can 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..");    
        }  
    }

, 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));
    }
+1

Source: https://habr.com/ru/post/1696048/


All Articles