我需要在 OnStop 方法中终止 Windows 服务中的任务吗? [英] Do I need to terminate Task in windows service in OnStop method?
问题描述
所以我有一个 Windows 服务我在 OnStart 开始任务
So I have a Windows Service And I started task in OnStart
partial class AppServices : ServiceBase
{
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
private Task _task;
public AppServices()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Log.Info("Service started");
_task = Task.Factory.StartNew(StartWork, TaskCreationOptions.LongRunning);
}
protected override void OnStop()
{
Log.Info("Service stopped");
}
private void StartWork()
{
while(true)
{
// grab some data from db or services
}
}
我需要在 OnStop 中添加 CancellationToken 并停止 Task 还是没有必要?因为服务何时停止 - 任务也会停止.安全不安全?
Do I need to add CancellationToken and stop Task in OnStop or it is unnecessary? Because when service will stop - Task stops as well. Does it safe or not?
推荐答案
您正以每小时 130 公里的速度行驶在高速公路上.突然你看到一个警察叫你停下来.当你注意到他时,你就在 A 点.您可以:
You're driving down the highway at 130 kmph. Suddenly you see a policeman who tells you to stop. When you notice him you are in point A. You can either:
- 无视他的命令
- 立即停车(在 A 点)改变车道并发生大爆炸.
- 逐渐但安全地停车,降低车速,最终在 B 点达到 0 公里/小时.B 点尽可能靠近 A 点,但在不危及任何人的情况下尽可能靠近.
在现实生活中,任何人都会选择 3).在 .NET 中,根据应用程序的性质和重要性,您也可以选择 1) 或 2).
In real life anyone would choose 3). In .NET, depending on the nature and importance of your application you could choose 1) or 2) also.
这取决于你是否愿意冒险:
It depends on you whether you want to risk:
- 被警察追捕(被任务管理器杀死)
- 崩溃(丢失重要数据或导致不一致等等)
- 完全没有
这篇关于我需要在 OnStop 方法中终止 Windows 服务中的任务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!