Task chaining without TaskCompletionSource?

前端 未结 3 752
故里飘歌
故里飘歌 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: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 where T: class
    {
       public T Value { get; set; }
    }
    
    public Task> Get() {
      var invokeTask = Invoke("GET");
      var result = invokeTask.ContinueWith>(t1 => {
        var holder = new Holder();
        var memorizeTask = t1.Result.Memorize();
        memorizeTask.ContinueWith(t2 => {
          holder.Value = t2.Result;
        }, TaskContinuationOptions.AttachedToParent);
        return holder;
      });
      return result;
    }
    

提交回复
热议问题