C#5.0中的等待和等待者 [英] The awaitable and awaiter In C# 5.0 Asynchronous

查看:112
本文介绍了C#5.0中的等待和等待者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务或任务< TResult>对象是可以等待的,因此我们可以对返回值为Task或Task< TResult>的对象使用await键. 任务或任务< TResult>是最常用的等待对象.

Task or Task<TResult> object is awaitable, so we can use await key on those whose return value is Task or Task<TResult>. Task or Task<TResult> are the most frequently-used awaitable object.

我们还可以定义自己的等待对象.该对象应具有以下限定条件.

We also can define our own awaitable object.The object should has below qualification.

  1. 它具有GetAwaiter()方法(实例方法或扩展方法);
  2. 其GetAwaiter()方法返回一个等待者.一个对象是一个等待者 如果:
    • 它实现INotifyCompletion或ICriticalNotifyCompletion 界面;
    • 它具有一个IsCompleted,它具有一个吸气剂并返回一个布尔值;
    • 它具有GetResult()方法,该方法返回void或结果.
  1. It has a GetAwaiter() method (instance method or extension method);
  2. Its GetAwaiter() method returns an awaiter. An object is an awaiter if:
    • It implements INotifyCompletion or ICriticalNotifyCompletion interface;
    • It has an IsCompleted, which has a getter and returns a Boolean;
    • it has a GetResult() method, which returns void, or a result.

我的问题是,为什么Microsoft不提供限制这些等待对象的接口? 当前实现等待对象的方法有点复杂.

My question is that why Microsoft didn't provide a interface to constrain these awaitable object? The current method to implement awaitable object is a little complicated.

推荐答案

最好在Lucian Wischik的博客文章

It is best answered in Lucian Wischik's blog post Why must async methods return Task?

总而言之(我不是在做博客文章的司法裁判,您应该阅读它),问题是Task已经存在,因此引入接口意味着

In summary (and I am not doing the blog post justice, you should read it), the issue is that Task already exists, so introducing an interface would mean

  • 所有内部方法都需要更改为接口,进行中断更改,因此对于框架人员来说,几乎不可能做到.
  • 作为程序员,您将经常需要确定是否要返回Task或接口,这一决定无关紧要.
  • 编译器将始终需要具体的类型,因此即使您从方法返回了接口,也仍将其编译为Task.
  • All the internal methods would need to be changed to the interface, a break change and thus almost impossible for the framework people to willingly do.
  • As a programmer you would constantly need to decide if you want to return Task or the interface, a decision that doesn't matter much.
  • The compiler would always need a concrete type, so even if you returned an interface from a method then it would still be compiled as Task.

以上所带来的影响是如此之大,以至于提供一个界面都没有意义.

The impact from the above is so massive that it doesn't make sense to provide an interface.

这篇关于C#5.0中的等待和等待者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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