Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage a list of tasks using the Task Parallel Library

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.

like image 451
farbodg Avatar asked Sep 16 '25 16:09

farbodg


1 Answers

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());
like image 167
i3arnon Avatar answered Sep 19 '25 04:09

i3arnon