Correct use of CancellationToken

BlueCastle picture BlueCastle · Mar 23, 2016 · Viewed 10.4k times · Source

This is my situation:

    private CancellationTokenSource cancellationTokenSource;
    private CancellationToken cancellationToken;

    public IoTHub()
    {
        cancellationTokenSource = new CancellationTokenSource();
        cancellationToken = cancellationTokenSource.Token;

        receive();
    }

    private void receive()
    {
        eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);
        var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

        foreach (string partition in d2cPartitions)
        {
            ReceiveMessagesFromDeviceAsync(partition, cancellationToken);
        }
    }

    private async Task ReceiveMessagesFromDeviceAsync(CancellationToken ct)
    {
        var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

        while (true)
        {
            if(ct.IsCancellationRequested)
            {
                break;
            }

            EventData eventData = await eventHubReceiver.ReceiveAsync();
            if (eventData == null) continue;

            string data = Encoding.UTF8.GetString(eventData.GetBytes());

            // Javascript function with Websocket
            Clients.All.setMessage(data);
        }
    }

    public void cancelToken()
    {
      cancellationTokenSource.Cancel();
    }

The Task will not be cancelled, when calling the cancelToken method. How come?

I have read the Microsoft guide, an other Stackoverflow questions about Task cancellation.

But still have difficulty using them correctly.

Answer

Cheng Chen picture Cheng Chen · Mar 23, 2016

You can consider CancellationToken like a flag, indicating if a cancellation signal is received. Thus:

while (true)
{
    //you check the "flag" here, to see if the operation is cancelled, correct usage
    if(ct.IsCancellationRequested)
    {
        break;
    }

    //your instance of CancellationToken (ct) can't stop this task from running
    await LongRunningTask();
}

If you want LongRunningTask to be cancelled, you should use CancellationToken inside the task body and check it when necessary, like this:

async Task LongRunningTask()
{
    await DoPrepareWorkAsync();

    if (ct.IsCancellationRequested)
    {
        //it's cancelled!
        return;
    }

    //let's do it
    await DoItAsync();

    if (ct.IsCancellationRequested)
    {
        //oh, it's cancelled after we already did something!
        //fortunately we have rollback function
        await RollbackAsync();
    }
}