本文介绍了自awaitables傻瓜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步/等待常见问题解答,斯蒂芬Toub说:

In Async/Await FAQ, Stephen Toub says:

这是 awaitable 是任何类型的暴露了一个 GetAwaiter 方法,该方法返回一个有效的 awaiter 的。照片  ...
  一个 awaiter 任何的从的 awaitable 的的 GetAwaiter 方法和符合返回类型到特定的图案。

因此​​,为了成为一个的 awaiter 的,一种类型的应:

So in order to be an awaiter, a type should:

  • 实施<$c$c>INotifyCompletion接口。
  • 提供称为布尔属性 IsCompleted
  • 提供一个无参数调用getResult 方法,返回无效 TResult
  • Implement the INotifyCompletion interface.
  • Provide a boolean property called IsCompleted.
  • Provide a parameterless GetResult method that returns void or TResult.

我忽略 ICriticalNotifyCompletion 现在的)

但什么是那些成员?我知道我上面提到的同一页面有一个示例,演示如何编译器将等待的操作,但我只是不明白这一点的。

But what are those members for?I know the same page I mentioned above has a sample that shows how the compiler translates await operations but I just don't get it.

谁能解释这些尽可能简单,像告诉它一个5岁?
当我的计谋的的的 awaitable

Could anyone explain these as simple as possible like telling it to a 5 years old?
When I await an awaitable,

  • 在什么情况下,code检查 IsCompleted ?我应该在哪里设置?
  • 当它调用 OnCompleted
  • 是否叫 OnCompleted 并行还是应该放在 OnCompleted 的code是异步的?
  • 在我看到这两个实例直接调用 OnCompleted 的延续参数,并使用 Task.Run(续)的不同的例子,这应该我去当?
  • When does the code checks IsCompleted? Where should I set it?
  • When does it call OnCompleted?
  • Does it call OnCompleted in parallel or should the code inside OnCompleted be asynchronous?
  • I saw examples of both directly invoking the continuation parameter of OnCompleted and using Task.Run(continuation) in different examples, which should I go for and when?

推荐答案

为什么要自定义awaiter?

Why would you want a custom awaiter?

您可以看到编译器的跨$ P $的计谋 here.从本质上讲:

You can see the compiler's interpretation of await here. Essentially:

var temp = e.GetAwaiter();
if (!temp.IsCompleted)
{
  SAVE_STATE()
  temp.OnCompleted(&cont);
  return;

cont:
  RESTORE_STATE()
}
var i = temp.GetResult();

的评论编辑: OnCompleted 应安排其作为一个持续的异步操作的参数

Edit from comments: OnCompleted should schedule its argument as a continuation of the asynchronous operation.

这篇关于自awaitables傻瓜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-24 07:12