Task chaining without TaskCompletionSource?

前端 未结 3 753
故里飘歌
故里飘歌 2021-01-05 12:53

I\'m converting some async/await code to chained tasks, so I can use it in the released framework. The await code looks like this

public async Task

        
相关标签:
3条回答
  • 2021-01-05 13:18

    I think that's pretty much the only way to accomplish what you want. Chaining disparate Tasks together isn't supported by the continuation APIs, so you have to resort to using a TaskCompletionSource like you have to coordinate the work.

    I don't have the Async CTP installed on this machine, but why don't you take a look at the code with a decompiler (or ILDASM if you know how to read IL) to see what it's doing. I bet it does something very similar to your TCS code under the covers.

    0 讨论(0)
  • 2021-01-05 13:21

    You can use attached child tasks. The parent task will only transition into the completed status when all child tasks are complete. Exceptions are propagated to the parent task. You will need a result holder, as the result will be assigned after the parent task's delegate has finished, but will be set when the parent tasks continuations are run.

    Like this:

    public class Holder<T> where T: class
    {
       public T Value { get; set; }
    }
    
    public Task<Holder<TraumMessage>> Get() {
      var invokeTask = Invoke("GET");
      var result = invokeTask.ContinueWith<Holder<TraumMessage>>(t1 => {
        var holder = new Holder<TraumMessage>();
        var memorizeTask = t1.Result.Memorize();
        memorizeTask.ContinueWith(t2 => {
          holder.Value = t2.Result;
        }, TaskContinuationOptions.AttachedToParent);
        return holder;
      });
      return result;
    }
    
    0 讨论(0)
  • 2021-01-05 13:23

    Yes, the framework comes with a handy Unwrap() extension method for exactly what you want.

    Invoke("GET").ContinueWith( t => t.Result.Memorize() ).Unwrap();
    

    If you're doing cancellation then you'll need to pass cancel tokens into the appropriate places, obviously.

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