[英]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 后它仍然運行? 我看到了很多關於不同解決方案的東西,其中一些阻塞線程,而另一些則沒有,所以這對我來說有點令人困惑,因為我是新手。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.