简体   繁体   中英

Cancel Async Task with CancellationTokenSource from a button click not working

What I need to do is able to cancel a task that is running async. Task should be cancelled on cancel button click. I have done it with CancellationTokenSource . But it is not working properly.

public class classA 
{
    CancellationTokenSource _tokenSource = null;

    public void OnCancelButtonClick()
    {
        MessageBox.Show("Do you Really want to cancel upload");            
        _tokenSource = new CancellationTokenSource();
        _tokenSource.Cancel();
    }

    public async void UploadBtnClick(object param )
    {
        _tokenSource = new CancellationTokenSource();
        var token = _tokenSource.Token;
        try
        {
            await Task.Run(() => UploadFunction(token));
        }
        catch(OperationCanceledException ex)
        {
            MessageBox.Show(ex.Message);

        }
        finally
        {
            _tokenSource.Dispose();
        }
    }

    public Task<bool> UploadFunction(CancellationToken token)
    {
        foreach
        {
            //code here

            if (token.IsCancellationRequested)
            {
                token.ThrowIfCancellationRequested();
            }
        }          
    }
}

I am calling OnCancelButtonClick from another function

public class classB 
{
    public void CancelUploadBtnExecute(object param)
    {
        FilesViewModel vm = new FilesViewModel();
        vm.OnCancelButtonClick(); 
    }
}

when I click on OnCancelButtonClick , IsCancellationRequested is false , but not reflected inside UploadFunction so the task won't stop.

It's because you are initializing new CancellationTokenSource in OnCancelButtonClick() .

Just remove this line from OnCancelButtonClick()

_tokenSource = new CancellationTokenSource();

UploadFunction method is using token created from CancellationTokenSource in UploadBtnClick method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM