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

问题描述

在Azure函数的性能注意事项"部分中, 功能最佳实践" 中的使用异步代码但避免阻塞调用"下的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.但是,由于它在后台运行,因此函数运行时假定消息已被成功使用并完成.如果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}");
    }
}

Functions运行时允许您使函数异步并返回Task.

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
查看更多