从旧版 .NET Framework 迁移时,我需要创建一个长时间的后台进程工作线程。
查看文档我发现了一个BackgroundService
类,就是用于这种目的的。但我偶然发现了两种相同的(就我的观点而言)方法ExecuteAsync()
and StartAsync()
有人可以向我解释一下它们之间的主要区别是什么吗?
这是某种隔离原则吗?我们有一种将数据设置为“构造函数”的方法,并且我们有一种实际做事的方法?
默认行为BackgroundService
就是它StartAsync
calls ExecuteAsync
, see code https://github.com/aspnet/Hosting/blob/master/src/Microsoft.Extensions.Hosting.Abstractions/BackgroundService.cs。这是默认的,StartAsync
is virtual
这样你就可以覆盖它。
请注意,仅StartAsync https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice.startasync?view=dotnet-plat-ext-3.1#Microsoft_Extensions_Hosting_BackgroundService_StartAsync_System_Threading_CancellationToken_ is public
and ExecuteAsync https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice.executeasync?view=dotnet-plat-ext-3.1#Microsoft_Extensions_Hosting_BackgroundService_ExecuteAsync_System_Threading_CancellationToken_
protected
(and abstract
)。所以从外面看StartAsync
叫做
如果你创建一个子类BackgroundService
, you must实施ExecuteAsync
(因为它是abstract
)。那应该可以完成你的工作。还有你could覆盖StartAsync
(就像它一样virtual
),但这仅适用于特殊情况。
那么为什么会有 StartAsync 和 ExecuteAsync 呢?
您可以通过实施来创建服务IHostedService https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.ihostedservice?view=dotnet-plat-ext-3.1。那个接口有StartAsync
and StopAsync
.
BackgroundService
是一个(基本)实现IHostedService
,并且可用于长时间运行的任务。这定义了摘要ExecuteAsync
.
总之
- 当继承自
BackgroundService
, 实施ExecuteAsync
- 实施时
IHostedService
, 实施StartAsync
and StopAsync
阅读更多
-
.NET Core 中的后台服务用于长时间运行的任务 https://medium.com/@daniel.sagita/backgroundservice-for-a-long-running-work-3debe8f8d25b- 此处还显示了 IHostedService 的其他实现,例如 TimedHostedService
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)