9

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.

Mafii
  • 7,227
  • 1
  • 35
  • 55
BlueCastle
  • 217
  • 2
  • 8
  • 18

1 Answers1

8

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();
    }
}
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • Could you explain this with an example? – BlueCastle Mar 23 '16 at 09:17
  • If cancellationTokenSource.Cancel() is called inside the constructor, the Task is cancelled. But the Task won't cancel when cancellationTokenSource.Cancel() is called from the cancelToken method. – BlueCastle Mar 23 '16 at 09:38
  • @BlueCastle This is probably because when you call `cancelToken()`, the statement `if (ct.IsCancellationRequested)` is already passed, in the following code, you will not check it again. – Cheng Chen Mar 23 '16 at 09:56