53

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.

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60
Mandar Jogalekar
  • 3,199
  • 7
  • 44
  • 85
  • 2
    Task.Run runs in the background but it still consumes another thread. Don't use it when you can await an async call and always avoid it for IO bound work. – Crowcoder Jan 19 '18 at 11:34

1 Answers1

87

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.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • 1
    But async functions cannot have a ref or out parameter, so how to do output bindings from an async function. – user2202866 Jul 26 '18 at 18:34
  • 2
    @user2202866 Like this: https://stackoverflow.com/a/40409345/1658906. TL;DR: Bind the return value or use IAsyncCollector. – juunas Jul 30 '18 at 19:33