Sto*_*orm 5 c# task-parallel-library asp.net-core c#-8.0 asp.net-core-3.1
我不知道我是否遗漏了这个难题的一部分,但就我习惯使用一般服务而言,任何对服务的调用都Start应该总是返回,以便您知道您的服务已经启动。
我正在学习BackgroundService:
ASP.NET Core 中托管服务的后台任务
使用 IHostedService 和 BackgroundService 类在微服务中实现后台任务
在这两个示例中,它们正在实现ExecuteAsync(由 调用StartAsync),使用的while loop含义是ExecuteAsync(并且通过扩展StartAsync)只有在取消时(例如应用程序关闭时)才会返回。
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogDebug($"GracePeriod task doing background work.");
// This eShopOnContainers method is querying a database table
// and publishing events into the Event Bus (RabbitMQ / ServiceBus)
CheckConfirmedGracePeriodOrders();
await Task.Delay(_settings.CheckUpdateTime, stoppingToken);
}
}
Run Code Online (Sandbox Code Playgroud)
这与我对服务的理解相矛盾,因为你如何判断服务已成功启动还是在启动时挂起?
我真的很感激对此有一些澄清,因为我似乎无法理解正在发生的事情,而且我似乎无法找到任何具体于此的进一步信息。
编辑:添加了对ExecuteAsyncfrom 的调用BackgroundService以进行说明:
public virtual Task StartAsync(CancellationToken cancellationToken)
{
// Store the task we're executing
_executingTask = ExecuteAsync(_stoppingCts.Token);
// If the task is completed then return it,
// this will bubble cancellation and failure to the caller
if (_executingTask.IsCompleted)
{
return _executingTask;
}
// Otherwise it's running
return Task.CompletedTask;
}
Run Code Online (Sandbox Code Playgroud)
通过 的魔力async,尽管ExecuteAsync看起来是一个无限循环,但它确实将 a 返回Task给调用者。延迟await允许控制流离开函数ExecuteAsync,循环的下一次迭代仅在Task解决后运行。
如果你不习惯的话,很容易错过。
| 归档时间: |
|
| 查看次数: |
2662 次 |
| 最近记录: |