Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I tried to work with Cancellationtoken but it wont work

So basically I tried following some Tutorials und examples on how to cancel an Task.

  • I understand, that you need a CancellationTokenSource token out of which you can extract a token that you need as an parameter (CancellationToken token) for the Task you want to stop

My problem is: when i press the "cancel"Button nothing stops.

Here is the general Code to that (I am using blazor Web Server)
.razor:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Button Clicked="@StartTask"> start </Button>
<Button Clicked="@StopTask"> cancel </Button>  //onlyshown when task runs

@code{
    static CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
    CancellationToken token = cancellationTokenSource.Token; 
    
    
    public Task StartTask()
    {
       await DoSomeApiStuff(token);
    }
    
    public Task StopTask()
    {
       cancellationTokenSource.Cancel();
    }
}
    

.cs file:

async Task DoSomeApiStuff(CancellationToken token)
{
   if (token.IsCancellationRequested)
            {
                return;
            }
    //Here is a really long Api and Saving in Database process
}

Do I miss something inside the Task I want to cancel?

>Solution :

This won´t work because you check your token only once. By the time you press the stop button the code has stepped over your if clause.

You would need to check the token more often while you do //Here is a really long Api and Saving in Database process or pass it to functions that support CancellationTokens

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading