在.NET 4.0中等待替代?

什么是.NET 4.0中await关键字的最佳替代方案? 我有一个方法,需要在异步操作后返回一个值。 我注意到wait()方法完全阻塞了线程,从而使异步操作无效。 在释放UI线程的同时运行异步操作有哪些选择?

我认为你的基本选择是

  • 使用Task.ContinueWith()
  • 使用Async CTP和async / await
  • 使用Reactive Extensions

最简单的方法可能是安装Async CTP。 据我所知,许可证允许商业用途。 它会对编译器进行修补,并附带一个150kb的dll,您可以将其包含在项目中。

您可以使用Task.ContinueWith() 。 但这意味着,您必须在exeption处理和流量控制方面付出一些努力。

任务是一个function构造。 这就是为什么ContinueWith()for循环或try-catch块等命令式结构不能很好地混合的原因。 因此asyncawait被引入,以便编译器可以帮助我们。

如果您不能获得编译器的支持(即使用.Net 4.0),最好的办法是将TAP与function框架一起使用。 Reactive Extensions是一个非常好的框架来处理异步方法。

只需谷歌“react native扩展任务”即可开始使用。

您可以使用yield协程实现类似await的行为,我在非4.5代码中使用它。 您需要一个YieldInstruction类,该类从应该运行异步的方法中检索:

 public abstract class YieldInstruction { public abstract Boolean IsFinished(); } 

然后你需要一些YieldInstruction实现(ae TaskCoroutine来处理一个任务)并以这种方式使用它(伪代码):

 public IEnumerator DoAsync() { HttpClient client = ....; String result; yield return new TaskCoroutine(() => { result = client.DownloadAsync(); }); // Process result here } 

现在您需要一个处理指令执行的调度程序。

 for (Coroutine item in coroutines) { if (item.CurrentInstruction.IsFinished()) { // Move to the next instruction and check if coroutine has been finished if (item.MoveNext()) Remove(item); } } 

在开发WPF或WinForms应用程序时,如果要在正确的时间更新协程,则还可以避免任何Invoke调用。 您也可以扩展这个想法,让您的生活更轻松。 样品:

 public IEnumerator DoAsync() { HttpClient client = ....; client.DownloadAsync(..); String result; while (client.IsDownloading) { // Update the progress bar progressBar.Value = client.Progress; // Wait one update yield return YieldInstruction.WaitOneUpdate; } // Process result here }