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.