Asynchronuous Processing

Asynchronuous processing is a feature you might not use that often. Below link explains the concept: Link: Asynchronuous Programming.

I needed the asynchronous call in an Azure function. More specifically I had to trigger a logic app for four different regions. I found however that if one of the regions failed, the processing of the other regions was skipped. That’s when I thought of processing the logic apps asynchronuously.

First I changed the signature of the Azure function to an asynchronuous method:

public static async Task Run(TimerInfo schedule, TraceWriter log)
instead of: public static void Run(TimerInfo schedule, TraceWriter log).

Next I changed the call to the logic app:
await Task.Run(() => client.PostAsync(logicAppUri, new StringContent(content, Encoding.UTF8, “application/json”)));
instead of: var response = client.PostAsync(logicAppUri, new StringContent(content, Encoding.UTF8, “application/json”)).Result;

Trace an async program

Unforunately, this option didn’t work. For that reason I turned to another option using Parallel.ForEach, instead of the regular ForEach. See: Link MSDN. The function is implemented as follows:

using System;
using System.Threading.Tasks;Link MSDN
using System.Net.Http;
using System.Text;

private static string logicAppUri = Environment.GetEnvironmentVariable(“ProcessAGAEventsURI”);
private static string content;

public static void Run(TimerInfo schedule, TraceWriter log)
{

string[] regions = new string[4];
regions[0]=”North”;
regions[1]=”South”;
regions[2]=”East”;
regions[3]=”West”;

Parallel.ForEach(regions, (regionCode) =>
//foreach (string regionCode in regions)
{
log.Info($”regionCode: {regionCode}”);
using (var client = new HttpClient())
{
var response = client.PostAsync(logicAppUri, new StringContent(content, Encoding.UTF8, “application/json”)).Result;
}
});
}

Leave a Reply

Your email address will not be published. Required fields are marked *