The awaitable and awaiter In C# 5.0 Asynchronous

后端 未结 3 1839
醉酒成梦
醉酒成梦 2021-02-07 18:48

Task or Task object is awaitable, so we can use await key on those whose return value is Task or Task. Task or Task are the most fr

3条回答
  •  一生所求
    2021-02-07 19:30

    This is in line with what they did for the foreach keyword (see section 8.8.4 of the C# language specification "The foreach statement").

    Basically, it's duck-typing; if the type implements a MoveNext method and a Current property, that's all that's needed for the C# compiler to know how to iterate through a sequence exposed by an object.

    This also applies with collection initializers (see section 7.6.10.3 of the C# language specification "Collection Initializers"); the only requirement is that the type implements the System.Collections.IEnumerable interface and have an Add method.

    That said, the await keyword just sticks to prior precedent, not requiring specific interface implementations (although the interfaces supply those methods if you choose to use them), just a pattern of methods that the compiler can recognize.

提交回复
热议问题