I'm trying to manage a list of tasks for a Windows Service so when I shut down the Service, I can use the Task.WaitAll() method to stop the Service from shutting down until all of the remaining tasks complete. For example, I have a Run() method that executes until a boolean is updated:
public void Run()
{
while (runFlag)
{
if (MaxTasksAchieved)
{
System.Threading.Thread.Sleep(pollingInterval);
}
else
{
taskList.Add(Task.Factory.StartNew(() =>
{
// do stuff
}));
}
}
}
Then in my Stop() method, I have the following:
public void Stop()
{
runFlag = false;
if (taskList.Count > 0)
{
// wait
Task.WaitAll(taskList.ToArray());
}
else
{
// no wait, great.
}
}
My question is how do I elegantly have the task remove itself from the list after it's done executing? I want the task to remove itself from the list so when Stop() is called, taskList only contains the tasks that are currently in progress.
If you want to remove the task from the list simply add a continuation that does that:
taskList.Add(task.ContinueWith(t = > taskList.Remove(t)));
But you can simply use Task.WaitAll
on all the tasks since the completed tasks are already completed.
Task.WaitAll(taskList.ToArray());
You can easily wait only on the running tasks by filtering the list with the tasks status
Task.WaitAll(taskList.Where(t => t.Status != TaskStatus.RanToCompletion).ToArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With