0

I have to stop the API execution through the Cancellation Token, In my method no for loops to check every time the cancellation requests, how to achieve it. I am using .NET core API

I have tried the below code

private string GetData(CancellationToken cancellationToken)
{
  
    try
    {
       if (cancellationToken.IsCancellationRequested)
           {
                _cts.Cancel();
                return "Task Cancelled";
           }  
        if (condition)
        {
            //Business Logic
        }
        else
        {
            //Business Logic
        }
    }
    catch (Exception e)
    {
        return e.Message.ToString(); ;
    }
}
1
  • You have to check the cancellation token inside //Business Logic, probably at various places, terminating early if the token has been cancelled. Commented Nov 7, 2024 at 13:43

1 Answer 1

0

We can use CancellationToken to stop the execution of the API without using a loop. The key is to check the cancellation request at the right place and take action (such as throwing an exception or returning directly) to terminate the task.

private string GetData(CancellationToken cancellationToken)
{
    try
    {
        if (cancellationToken.IsCancellationRequested)
        {
            throw new OperationCanceledException("Task was canceled.");
        }
        if (condition)
        {
            // Business Logic
        }
        else
        {
            // Business Logic
        }

        return "Data Retrieved Successfully";
    }
    catch (OperationCanceledException)
    {
        return "Task Cancelled";
    }
    catch (Exception e)
    {
        return e.Message;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.