Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a state object to a continuation task?

Tags:

I'm using the .NET 4.0 Task Parallel Library with C# (my first time using TPL)

I have a task A which I want to run to completion before firing off a bunch of other tasks (B,C,D, etc). I therefore want to create tasks B,C,D etc as continuations of task A. However, I want to pass a 'state' object to task B, another state object to task C, etc.

I can pass a state object to task A by simply using a Task constructor overload that takes a state object, for example http://msdn.microsoft.com/en-us/library/dd783035.aspx describes this Task constructor overload:

Task(Action<Object>, Object, CancellationToken) 

This works fine, and the second argument is my 'state' object.

I want to create a continuation task, e.g. for task B:

Task taskB = taskA.ContinueWith(/* args here*/)

However, I cannot see a ContinueWith() overload (see http://msdn.microsoft.com/en-us/library/dd235663.aspx) which allows me to pass a 'state' object to a continuation task. How can this be done?

Notes:

  1. I do not have the 'state' object for taskB available at the time I create taskA
  2. The 'state' object for taskB is not an output (return value) of taskA

For some context, what I am doing is creating taskB, taskC, etc. inside a couple of loops and so I am passing the value of the loop variables to taskB, taskC, etc. using a state object, in order to avoid the problem of always ending up with the final value of the loop variables in the tasks (the closure issue).

like image 410
Hugh Robinson Avatar asked May 13 '11 14:05

Hugh Robinson


People also ask

What is task continuation?

A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.

What does calling task ContinueWith () do?

ContinueWith(Action<Task>)Creates a continuation that executes asynchronously when the target Task completes.

Which code creates a chain of task to be executed after one another?

c# - Run sequence of tasks, one after the other - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What does Task run do C#?

The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. It creates a task with the following default values: Its cancellation token is CancellationToken.


1 Answers

The simplest approach would probably be to simply capture it in the Func<Task, TResult> you pass into ContinueWith. For example:

object taskBState = GetStateHere();
Task taskB = taskA.ContinueWith(task => RealContinuation(task, taskBState));

Personally I find it easier to capture state like that than getting the state passed in anyway.

like image 167
Jon Skeet Avatar answered Sep 18 '22 08:09

Jon Skeet