I\'m attempting to programmatically chain asynchronous operations in C#4, such as Writes to a given Stream object. I originally did this \"manually\", hooking callbacks from one
Try ContinueWhenAll()
or ContinueWhenAny()
instead of ContinueWith()
.
See here.
My best idea so far is to chain the creation of the new write task, then use the Unwrap extension method to turn Task<Task>
back into Task
:
public static Task ChainWrite(Stream stream, byte[] data, Task precedingTask)
{
return precedingTask.ContinueWith(x => CreateWriteTask(stream, data)).Unwrap();
}
As far as I understand it, this is an unfortunate consequence of not being in control over when a task gets started. Since you never know when a task gets started, there can't be an overload like
precedingTask.ContinueWith(Task nextTask)
because once created, it might already be started when you get to 'ContinueWith'. Besides, it would also make a mess of types. What should be the type here:
precedingTask<T>.ContinueWith(Task<..what?..> nextTask)
preceding returns a T, so next takes what and returns what? :) This could be solved with closures though.