I want to chain Tasks, then start the chain in parallel.
This snippet is just to illustrate my question:
var taskOrig = new Task(() => { });
var task = taskOrig;
foreach (var msg in messages)
{
task=task.ContinueWith(t => Console.WriteLine(msg));
}
taskOrig.Start();
Everything works fine except a little perfectionist inside me doesn’t like having empty method executed first () => { }.
Is there any way to avoid it?
I do understand It’s barely affecting performance (unless you do it really often), but still. Performance matters in my case, so checking if task exists in every iteration is not the way to do it.
You could do this:
The previous solution won’t work in 4.0. In 4.0 you’d need to do the following instead:
(You can move
SetResultto before the foreach loop if you prefer.)Technically it’s not the same as the continuations will start executing while you’re still adding more. That’s unlikely to be a problem though.
Another option would be to use something like this:
An example usage would be: