本文介绍了异步编程和 Azure 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Azure 函数性能注意事项"部分,Functions Best Practices,在使用异步代码但避免阻塞调用"下,async 编程是提高性能的建议做法.但是,最好的使用方法是什么?例如,在我的场景中,我有以下服务总线触发器:

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}");
    }
}

在上面的代码中,我调用了PushToDb方法async.但是,由于它在后台运行,因此 Function 运行时假定消息已成功消费并完成.如果 PushToDb 方法抛出异常怎么办?如何确保运行时知道它不完整,而是应该被放弃?

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?

希望尽可能多地使用 async 来提高性能.

Looking to use async as much as possible for performance.

推荐答案

你可以让函数异步:

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.

这篇关于异步编程和 Azure 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:18
查看更多