Skip to content

Commit e824bdc

Browse files
authored
Added update to Cancellation Token section
1 parent e1dc657 commit e824bdc

File tree

1 file changed

+36
-12
lines changed

1 file changed

+36
-12
lines changed

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

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -295,29 +295,53 @@ 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+
This is especially the case when you have functions that process messages in batch. Consider the following version 4 (~4) Service Bus triggered function. The default template for a Service Bus triggered Azure Function is rendered to accept a single message using this parameter: ```string myQueueItem```. By changing that single message parameter to an array like: ```Message[] messages```, results in the function receiving a batch of, or multiple, messages per 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
```
338+
A common pattern for iterating through an array uses the foreach statement. Within the foreach statement, prior to processing the message, check if a cancellation token has been generated. The most common scenario will be that the IsCancellationRequested property is false and, in that case, your coded business logic will execute. In a seldom, but realistic scenario that IsCancellationRequested is true, you will need to take some precautionary actions. For example, writing a log which stores the fact that this happened and perhaps store the portion of the message batch which has not yet been processed. If you do the latter, then your startup code needs to check if there are any message batches which experienced this shutdown procedure. The actual requirement is based on your specific scenario.
339+
Consider that processing messages in batches is possible with an Event Hub triggered function. Notice that the events parameter is declared as an array like the following, ```EventData[] events```.
340+
```csharp
341+
public async Task Run([EventHubTrigger("csharpguitar", Connection = "EH_CONN")]
342+
EventData[] events, CancellationToken cancellationToken, ILogger log)
343+
```
344+
The pattern to process a batch of events is the same as the one shown for processing a batch of Service Bus messages. In each case you should check for a cancellation token prior to the processing of each item in the array, and if present, manage it as per your business requirements.
321345

322346
## Logging
323347

0 commit comments

Comments
 (0)