Reputation: 1151
In the past, I've created the main thread of a service using the Thread object. Now I'm attempting to update it to the TPL. Unfortunately, the service ends after one pass in my loop. What do I need to do to keep the Task alive?
protected override void OnStart(string[] args)
{
_workerThread = Task.Run(() =>
{
while (true)
{
Console.WriteLine("go");
Thread.Sleep(10000);
}
});
}
More info:
In order to debug the service, I've set a flag to start the service as a console app if Environment.UserInteractive is set to true. So I guess I need it to keep going in console mode as well as a service.
Upvotes: 1
Views: 109
Reputation: 244928
When you create a new Thread
, it is a foreground thread by default (its IsBackground
is set to false
). What that means is that your console application won't end until the thread does, even if Main
returns before that.
Task
s, on the other hand, run on the thread pool, which contains only background threads. This means that when your Main
returns, the application will exit, even if there is some Task
still running.
You can fix this by Wait
ing on the Task
at the end of your Main
.
Upvotes: 1