How do I chain Asynchronous Operations with the Task Parallel library in .NET 4?

后端 未结 3 1472
长发绾君心
长发绾君心 2021-02-02 14:07

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

相关标签:
3条回答
  • 2021-02-02 14:35

    Try ContinueWhenAll() or ContinueWhenAny() instead of ContinueWith(). See here.

    0 讨论(0)
  • 2021-02-02 14:37

    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();
    }
    
    0 讨论(0)
  • 2021-02-02 14:54

    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.

    0 讨论(0)
提交回复
热议问题