繁体   English   中英

如何在任务完成之前返回但保持运行?

[英]How can I return before a task completes but keep it running?

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

// 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 后它仍然运行? 我看到了很多关于不同解决方案的东西,其中一些阻塞线程,而另一些则没有,所以这对我来说有点令人困惑,因为我是新手。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM