【发布时间】:2021-11-28 11:23:28
【问题描述】:
如果在 Azure 函数中启动了异步任务,但在完成之前孤立会发生什么情况(从不等待),例如:
[Function("FuncAsync")]
public static async Task<HttpResponseData> FuncAsync(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "FuncAsync")]
HttpRequestData req,
FunctionContext context)
{
var obj = FactoryClass.GetObject(); // return some object with async LongTaskAsync method
obj.LongTaskAsync(); // async Task LongTaskAsync()
return req.CreateResponse(HttpStatusCode.OK);
}
这里的意图是(我猜)启动一个长时间运行的进程并立即从函数返回。
我认为这是一种不好的做法,但似乎可以在遗留代码中使用。我怀疑该异步任务的生命周期无法保证,并且当没有函数入口点正在运行/触发时,天蓝色进程可能会随机结束。
对于控制台应用程序,如果正在运行的异步任务是孤立的(并在进程终止时继续运行),它将被放弃/杀死(并且不会引发异常)。
class Program
{
public static async Task RunFuncAsync()
{
try
{
Console.WriteLine("Task started.");
await Task.Delay(10 * 1000);
Console.WriteLine("Task finished."); // this is never executed
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message); // this is never executed
}
}
static async Task MainAsync(string[] args)
{
var t = RunFuncAsync(); // no awaiting - purposefuly
await Task.Delay(5 * 1000);
Console.WriteLine("Exiting.");
}
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
}
输出:
Task started.
Exiting.
C:\TestTasks_Console.exe (process 6528) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .
【问题讨论】:
标签: c# azure asp.net-core .net-core azure-functions