为什么Awaiters(异步/等待)结构,而不是类?可类中使用? [英] Why are Awaiters (async/await) structs and not classes? Can classes be used?

查看:155
本文介绍了为什么Awaiters(异步/等待)结构,而不是类?可类中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么是awaiters(GetAwaiter - 使一个类awaitable)结构,而不是类。是否危害到使用类?

Why are the awaiters (GetAwaiter - to make a class awaitable) structs and not classes. Does it harm to use a class?

public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion:

<一个href="http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs#b8626cdb2f1cbe65" rel="nofollow">http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs#b8626cdb2f1cbe65

public struct YieldAwaiter : ICriticalNotifyCompletion:

<一个href="http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/YieldAwaitable.cs#1e1219f924e9e3b7" rel="nofollow">http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/YieldAwaitable.cs#1e1219f924e9e3b7

public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion

<一个href="http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs#2c48fb3bdfc69022" rel="nofollow">http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs#2c48fb3bdfc69022

推荐答案

背后做的原因 awaitables A结构是为了避免不必要的堆分配,并尽量减少内存占用时,编译器创建的状态机在幕后。

The reason behind making awaitables a struct is to avoid unnecessary heap allocations and minimize the memory footprint when the compiler creates the state machine behind the scenes.

这是一个实现细节。对于awaitable是类型这是没有必要结构,而不是。为了加强这一说法,尝试编译Roslyn的异步方法在调试模式下,你会看到状态机变成一个类,其中,作为编纂发布将导致结构。更多关于在<一个href="http://stackoverflow.com/questions/33871181/why-are-async-state-machines-classes-and-not-structs-in-roslyn?newsletter=1&nl$c$c=493396%7c7764">Why是异步状态机类(而不是结构)的罗斯林?

This is an implementation detail. It is not necessary for an awaitable to be of type struct and not a class. To strengthen this statement, try compiling an async method in Roslyn in Debug mode, and you'll see the state-machine turn into a class, where-as compiling in Release will result in a struct. More on that in Why are async state machines classes (and not structs) in Roslyn?

这篇关于为什么Awaiters(异步/等待)结构,而不是类?可类中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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