Async programming and Azure functions

Mandar Jogalekar picture Mandar Jogalekar · Jan 19, 2018 · Viewed 21.1k times · Source

In the Azure functions "Performance considerations" part, Functions Best Practices, under "Use async code but avoid blocking calls", async programming is the suggested practice for performance improvement. However, what is the best way to use it? For example, in my scenario, I have the following Service Bus Trigger:

public static void Run(
    [ServiceBusTrigger("topicname", "subname", AccessRights.Manage, 
    Connection = "TopicConnection")]string message, TraceWriter log)
{
    try {
        log.Info($"C# ServiceBus topic trigger function processed message: {message}");

        Task.Run(() => PushToDb(message, log));
    }
    catch(Exception ex)
    {
        log.Info($"Exception found {ex.Message}");
    }
}

In the above code, I call PushToDb method async. However, since it runs in the background, Function runtime assumes that the messages are consumed successfully and completes it. What if the PushToDb method throws an exception? How can I make sure runtime knows that it's not complete, but rather should be abandoned?

Looking to use async as much as possible for performance.

Answer

juunas picture juunas · Jan 19, 2018

You can make the function async:

public static async Task Run(
    [ServiceBusTrigger("topicname", "subname", AccessRights.Manage, Connection = "TopicConnection")]string message,
    TraceWriter log)
{
    try
    {
        log.Info($"C# ServiceBus topic trigger function processed message: {message}");
        await PushToDb(message, log);
    }
    catch(Exception ex)
    {
        log.Info($"Exception found {ex.Message}");
    }
}

The Functions runtime allows you to make your function async and return a Task.

In this case we can just await the call so we can handle exceptions normally.