Home > Net >  How to handle CancellationToken in Azure function eventhub trigger
How to handle CancellationToken in Azure function eventhub trigger

Time:05-12

In an Azure function event hub trigger (v3) it takes in a cancellation token in the Run method. When cancellation is signaled it means the server it shutting down. If I send this token to for example a Get operation using httpClient it will throw a TaskCanceledException and the function will end.

Will the events that this function was processing be sent to another instance of the function on another server or are they lost? Should cancellation be handle in a different way?

[FunctionName(nameof(MyFunction)), FixedDelayRetry(10, "00:00:15")]
public async Task RunAsync(
   [EventHubTrigger("%InEventHubName%", 
     Connection = "InEventHubConnectionString", 
     ConsumerGroup = "%ConsumerGroup%")] 
   EventData[] events,
   PartitionContext partitionContext,
   CancellationToken cancellationToken)
{
       foreach (var ev in events)
       {
            var response = await _httpClient.GetAsync("http://example.com/fetch?key="   ev.Properties["Key"],
                             cancellationToken);
            await Process(response, cancellationToken);
       }
}

CodePudding user response:

Will the events that this function was processing be sent to another instance of the function on another server or are they lost?

They are lost:

Unhandled exceptions may cause you to lose messages. Executions that result in an exception will continue to progress the pointer.


Should cancellation be handle in a different way?

You could choose to ignore cancellation. That may be best for this kind of situation.

  • Related