Javier De Pedro
Javier De Pedro

Reputation: 2239

Generic call for StartNew and ContinueWhenAll

I'm not an expert in c# and quite new in TPL...

I have a lot of different task that I want to start and some depends on others. Also I want to decide from a xml config file if some of the task must be executed or not and then the ones depending on a task that is not going to be performed shall not wait until this task is executed.

Using if statements for all of this overcomplicates my code so I would like to do something like this:

static Task<bool> StartTask( List<Task<bool>> dependencies,
                             Func<bool> action)
{
    List<Task<bool>> filtered = new List<Task<bool>>();
    foreach (Task<bool> t in dependencies)
    {
        if (t != null)
        {
            filtered.Add(t);
        }
    }

    Task<bool> task;
    if (filtered.Count == 0)
    {
        task = (Task<bool>)tf.StartNew(action);
    }
    else
    {
        task = (Task<bool>)tf.ContinueWhenAll(filtered.ToArray(), ts => action);
    }

    return task;
}

So the idea is I generate the list of dependencies of every task at the beginning and then if any task is not performed filtering the list of null tasks...and if none of the ancestors of the task has been performed I call StartNew instead of ContinueWhenAll.....this way I set lists with the dependencies and call all the tasks in a generic way.

But I don't know whether this is doable and how to do it in c#. Any idea??

All the tasks returns bool but have different parameters.

Javier

Upvotes: 1

Views: 48

Answers (1)

usr
usr

Reputation: 171216

I'd write it like this:

await Task.WhenAll(dependencies.Where(t => t != null));
await Task.Run(() => action());

I'd make the Where(t => t != null) part an argument validation and make it illegal to pass null tasks.

Upvotes: 1

Related Questions