为什么能够以等待接收观察到的? [英] Why is it possible to await an Rx observable?

查看:160
本文介绍了为什么能够以等待接收观察到的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚才注意到,的await 关键字可以被用来与接收可观的,例如:

I have just noticed that the await keyword can be used with Rx Observable, for example:

await Observable.Interval(TimeSpan.FromHours(1));

我是pretty确保它只能结合使用的任务。

I was pretty sure that it can only be used in conjunction with Tasks.

那么是什么让这可能吗?是观测硬codeD的知识转化为编译器?

So what makes it possible? Is the knowledge of observables hard coded into the compiler?

推荐答案

没有,编译器的IObservable&LT没有特殊的知识; T> 。根据部分C#5规范的7.7.7.1如果对象有一个方法或者有范围扩展方法命名为 GetAwaiter 返回一个类型实现 System.Runtime.CompilerServices.INotifyCompletion ,也可以期待。见史蒂芬Toub的文章,恭候什么

No, the compiler has no special knowledge of IObservable<T>. As per section 7.7.7.1 of the C# 5 specification if the object has a method or there is an extension method in scope named GetAwaiter that returns a type that implements System.Runtime.CompilerServices.INotifyCompletion, it can be awaited. See Steven Toub's article, Await anything.

更具体地,从规范

一个AWAIT前pression的任务需要为awaitable。一名前pression的 T 的就是 awaitable 如果以下情况之一成立:结果
     - T 的是编译时动态类型的搜索
     - T 的有一个叫GetAwaiter无参数,无参数的类型可访问的实例或扩展方法,并返回类型为一所有下列条件成立:结果
     1.实现了接口System.Runtime.CompilerServices.INotifyCompletion(以下称为INotifyCompletion为简洁起见)结果
     2.具有IsCompleted bool类型结果的可访问性,可读性实例属性
     3.有没有参数和类型参数可访问实例方法调用getResult

The task of an await expression is required to be awaitable. An expression t is awaitable if one of the following holds:
- t is of compile time type dynamic
- t has an accessible instance or extension method called GetAwaiter with no parameters and no type parameters, and a return type A for which all of the following hold:
1. A implements the interface System.Runtime.CompilerServices.INotifyCompletion (hereafter known as INotifyCompletion for brevity)
2. A has an accessible, readable instance property IsCompleted of type bool
3. A has an accessible instance method GetResult with no parameters and no type parameters

请注意这是怎么类似于如何的foreach 不需要的IEnumerable&LT; T&GT; ,只是一个GetEnumerator方法是返回一个兼容的对象。这种鸭打字是一种性能优化,允许由编译器没有拳击使用的值的类型。这可用于避免在性能敏感code不必要的分配。

Note how this is similar to how foreach does not require IEnumerable<T> but simply a GetEnumerator method that returns a compatible object. This sort of duck typing is a performance optimization that allows value types to be used by the compiler without boxing. This can be used to avoid unnecessary allocations in performance sensitive code.

这篇关于为什么能够以等待接收观察到的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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