任务链没有TaskCompletionSource? [英] Task chaining without TaskCompletionSource?

查看:72
本文介绍了任务链没有TaskCompletionSource?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我把一些异步/的await code到链式任务,这样我就可以在公布的框架中使用它。该的await code看起来像这样

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<TraumMessage> Get() {
  var message = await Invoke("GET");
  var memorized = await message.Memorize();
  return memorized;
}

其中,

Task<TraumMessage> Invoke(string verb) {}
Task<TraumMessage> Memorize() {}

我希望链调用背诵来返回由生产任务背诵,但导致任务&LT;任务&LT; TraumMessage&GT; 。我已经结束了该解决方案是一个 TaskCompletionSource&LT; TraumMessage&GT; 我的信号:

I was hoping to chain Invoke and Memorize to return the task produced by Memorize, but that results in a Task<Task<TraumMessage>. The solution i've ended up is a TaskCompletionSource<TraumMessage> as my signal:

public Task<TraumMessage> Get() {
  var completion = new TaskCompletionSource<TraumMessage>();
  Invoke("GET").ContinueWith( t1 => {
     if(t1.IsFaulted) {
       completion.SetException(t1.Exception);
       return;
     }
     t1.Result.Memorize().ContinueWith( t2 => {
       if(t2.IsFaulted) {
         completion.SetException(t2.Exception);
         return;
       }
       completion.SetResult(t2.Result);
     });
  });
  return completion.Task;
}

有没有办法做到这一点,而不 TaskCompletionSource

推荐答案

我认为这是pretty大有作为你想要什么的唯一方式。链接不同的任务一起不被延续API的支持,因此你不得不求助于使用 TaskCompletionSource 一样,你必须协调工作。

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.

我没有这台机器上安装了CTP异步,但你为什么不看看在code用反编译(或ILDASM,如果你知道如何阅读IL),看看它在做什么。我敢打赌,它非常类似于您TCS code在幕后的东西。

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.

这篇关于任务链没有TaskCompletionSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆