C# 如何在任务完成之前返回,但保持其运行?
我有一个Azure函数,其中一个异步方法C# 如何在任务完成之前返回,但保持其运行?,c#,asynchronous,task,azure-functions,C#,Asynchronous,Task,Azure Functions,我有一个Azure函数,其中一个异步方法异步任务方法a调用异步任务方法b。由于MethodB预计需要的时间总是超过1分钟,我们需要在MethodB完成之前启动MethodB并返回MethodA中接受的202。在MethodB中,我们通过将信息存储在表中来跟踪状态。如果MethodB失败或抛出异常,我们将捕获异常并相应地更新表。这样,当客户端查询任务的状态时,它会从表中获取结果。以下是实际发生情况的伪代码: // The starting method. [FunctionName("Method
异步任务方法a
调用异步任务方法b
。由于MethodB
预计需要的时间总是超过1分钟,我们需要在MethodB
完成之前启动MethodB
并返回MethodA
中接受的202。在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.
}
//启动方法。
[函数名(“方法A”)]
公共静态异步任务方法A(
[HttpTrigger(AuthorizationLevel.Anonymous,“post”,Route=“start”)]HttpRequest请求,
ILogger(记录器)
{
//以某种方式启动MethodB,使其运行,我们可以在完成之前返回202 Accepted。
返回新的AcceptedResult();
}
专用静态异步任务方法B(ILogger记录器)
{
尝试
{
//将状态为“running”的行插入表中并进行日志记录。
//做一些耗时超过1分钟的事情,并做更多的日志记录。
}
catch(Exception)//非常通用的伪代码异常处理。
{
//将表中的行更新为状态“失败”,然后执行一些日志记录。
}
}
[函数名(“方法C”)
公共静态异步任务方法(
[HttpTrigger(AuthorizationLevel.Anonymous,“get”,Route=“get”)]HttpRequest请求,
ILogger(记录器)
{
//查找表中的行,获取状态,并进行日志记录。
//如果仍在运行或成功,则返回200 Ok,否则返回一些故障代码。
//还返回表中的确切状态,以区分正在运行和已成功。
}
有哪些选项可以启动
MethodB
,这样在我返回202 Accepted后它仍然可以运行?我看到了许多关于不同解决方案的事情,其中一些阻止线程,一些不阻止线程,所以这对我来说都有点让人困惑,因为我是新手。Azure函数支持持久函数。一个使用案例如中所述是一种异步HTTP API模式,用于启动长时间运行的任务,尽早返回,并支持稍后从客户端检查状态。根据方法a和B的详细信息,您可能也想将其用于,但听起来您确实可以使用持久函数,完全摆脱a和C,因为您正在尝试实现ey已经支持了。Nice!我以前从未听说过这些。异步HTTP API模式似乎正是我所寻找的,甚至可以帮助我避免查询状态的整个表场景。谢谢!