Search code examples
c#razorblazorcancellationtokensourcecancellation-token

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:

<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