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
}
}
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?
Tasks run as background threads. Thus, when the service stops, the task will be automatically stopped. Whether you need to formally cancel the task depends on whether the task needs to know it is exiting so that it can perform any necessary cleanup.
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:
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: