所以我有一个Windows服务,我在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
}
}
我是否需要添加的CancellationToken和调用OnStop停止工作或没有必要? 因为当服务将停止 - 任务将停止为好。 它是否安全呢?