首页 > 解决方案 > 如何在任务完成之前返回但保持运行?

问题描述

我有一个 Azure 函数,其中一个异步方法async Task<IActionResult> MethodA调用async Task MethodB. 由于MethodB预计总是需要超过 1 分钟,因此我们需要在完成前开始MethodB并返回 202 Accepted 。在内部,我们通过将信息存储在表格中来跟踪状态。如果失败或抛出异常,我们会捕获异常并相应地更新表。这样,当客户端查询任务的状态时,它会从表中获取结果。这是实际发生的伪代码:MethodAMethodBMethodBMethodB

// The starting method.
[FunctionName("MethodA")]
public static async Task<IActionResult> MethodA(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "start")] HttpRequest request,
    ILogger logger)
{
    // Somehow start MethodB so that it runs and we can return 202 Accepted before it finishes.
    return new AcceptedResult();
}

private static async Task MethodB(ILogger logger)
{
    try
    {
        // Insert row into table with status "running" and do logging.
        // Do stuff that takes longer than 1 minute and do more logging.
    }
    catch(Exception exception) // Very general exception handling for pseudo-code.
    {
        // Update row in table to status "failed" an do some logging.
    }
}

[FunctionName("MethodC")
public static async Task<IActionResult> MethodC(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "get")] HttpRequest request,
    ILogger logger)
{
    // Looks for row in table, gets the status, and do logging.
    // Returns 200 Ok if still running or succeeded, otherwise otherwise some failure code.
    // Also returns the exact status in the table to differentiate between running and succeeded.
}

有哪些启动选项MethodB可以在我返回 202 Accepted 后仍然运行?我看到了很多关于不同解决方案的东西,其中一些阻塞线程,而另一些则没有,所以这对我来说有点令人困惑,因为我是新手。

标签: c#asynchronoustaskazure-functions

解决方案


Azure 函数支持持久函数。文档中描述的一个用例是异步 HTTP API 模式,用于启动长时间运行的任务,提前返回并支持稍后检查客户端的状态。根据您的方法 A 和 B 的详细信息,您可能还希望将其用于链接,但听起来您确实可以使用持久函数并完全摆脱 A 和 C,因为您正在尝试实现它们已经支持的功能。


推荐阅读