Skip to content

Commit 9f6fb21

Browse files
authored
Merge pull request #87321 from benperk/patch-1
Added update to Cancellation Token section
2 parents 3fd641d + 71ec139 commit 9f6fb21

File tree

1 file changed

+40
-12
lines changed

1 file changed

+40
-12
lines changed

articles/azure-functions/functions-dotnet-class-library.md

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -295,30 +295,58 @@ You can't use `out` parameters in async functions. For output bindings, use the
295295

296296
A function can accept a [CancellationToken](/dotnet/api/system.threading.cancellationtoken) parameter, which enables the operating system to notify your code when the function is about to be terminated. You can use this notification to make sure the function doesn't terminate unexpectedly in a way that leaves data in an inconsistent state.
297297

298-
The following example shows how to check for impending function termination.
298+
Consider the case when you have a function that processes messages in batches. The following Azure Service Bus-triggered function processes an array of [Message](/dotnet/api/microsoft.azure.servicebus.message) objects, which represents a batch of incoming messages to be processed by a specific function invocation:
299299

300300
```csharp
301-
public static class CancellationTokenExample
301+
using Microsoft.Azure.ServiceBus;
302+
using System.Threading;
303+
304+
namespace ServiceBusCancellationToken
302305
{
303-
public static void Run(
304-
[QueueTrigger("inputqueue")] string inputText,
305-
TextWriter logger,
306-
CancellationToken token)
306+
public static class servicebus
307307
{
308-
for (int i = 0; i < 100; i++)
308+
[FunctionName("servicebus")]
309+
public static void Run([ServiceBusTrigger("csharpguitar", Connection = "SB_CONN")]
310+
Message[] messages, CancellationToken cancellationToken, ILogger log)
309311
{
310-
if (token.IsCancellationRequested)
312+
try
313+
{
314+
foreach (var message in messages)
315+
{
316+
if (cancellationToken.IsCancellationRequested)
317+
{
318+
log.LogInformation("A cancellation token was received. Taking precautionary actions.");
319+
//Take precautions like noting how far along you are with processing the batch
320+
log.LogInformation("Precautionary activities --complete--.");
321+
break;
322+
}
323+
else
324+
{
325+
//business logic as usual
326+
log.LogInformation($"Message: {message} was processed.");
327+
}
328+
}
329+
}
330+
catch (Exception ex)
311331
{
312-
logger.WriteLine("Function was cancelled at iteration {0}", i);
313-
break;
332+
log.LogInformation($"Something unexpected happened: {ex.Message}");
314333
}
315-
Thread.Sleep(5000);
316-
logger.WriteLine("Normal processing for queue message={0}", inputText);
317334
}
318335
}
319336
}
320337
```
321338

339+
As in the previous example, you commonly iterate through an array using a `foreach` loop. Within this loop and before processing the message, you should check the value of `cancellationToken.IsCancellationRequested` to see if cancellation is pending. In the case where `IsCancellationRequested` is `true`, you might need to take some actions to prepare for a graceful shutdown. For example, you might want to log the status of your code before the shutdown, or perhaps write to a persisted store the portion of the message batch which hasn't yet been processed. If you write this kind of information to a persisted store, your startup code needs to check the store for any unprocessed message batches that were written during shutdown. What your code needs to do during graceful shutdown depends on your specific scenario.
340+
341+
Azure Event Hubs is an other trigger that supports batch processing messages. The following example is a function method definition for an Event Hubs trigger with a cancellation token that accepts an incoming batch as an array of [EventData](/dotnet/api/microsoft.azure.eventhubs.eventdata) objects:
342+
343+
```csharp
344+
public async Task Run([EventHubTrigger("csharpguitar", Connection = "EH_CONN")]
345+
EventData[] events, CancellationToken cancellationToken, ILogger log)
346+
```
347+
348+
The pattern to process a batch of Event Hubs events is similar to the previous example of processing a batch of Service Bus messages. In each case, you should check the cancellation token for a cancellation state before processing each item in the array. When a pending shutdown is detected in the middle of the batch, handle it gracefully based on your business requirements.
349+
322350
## Logging
323351

324352
In your function code, you can write output to logs that appear as traces in Application Insights. The recommended way to write to the logs is to include a parameter of type [ILogger](/dotnet/api/microsoft.extensions.logging.ilogger), which is typically named `log`. Version 1.x of the Functions runtime used `TraceWriter`, which also writes to Application Insights, but doesn't support structured logging. Don't use `Console.Write` to write your logs, since this data isn't captured by Application Insights.

0 commit comments

Comments
 (0)