55

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.

1
  • 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. Commented Jan 19, 2018 at 11:34

1 Answer 1

89
Answer recommended by Microsoft Azure Collective

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But async functions cannot have a ref or out parameter, so how to do output bindings from an async function.
@user2202866 Like this: stackoverflow.com/a/40409345/1658906. TL;DR: Bind the return value or use IAsyncCollector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.