簡體   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