MemoryStream ReadAsync中的task有什么用?

What is the use of task in MemoryStream ReadAsync?

为什么 MemoryStream.ReadAsync 正在使用任务,即使代码没有任何 asyncawait。我确信在这里使用 async 不会带来任何性能提升,因为它不是 I/O 操作,而是内存操作。

看起来好像使用了一些缓存,但他们仍然调用同步读取方法

Read(buffer, offset, count)

那这里的任务有什么用呢?

它自己说明:

[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<int> ReadAsync

此方法是 Stream class 中基础 public virtual Task<int> ReadAsync 方法的 override。请注意,此覆盖逻辑仅在 定义了 FEATURE_ASYNC_IO 变量的情况下引入:

#if FEATURE_ASYNC_IO

这是一种通过基于 Task 的方法来实现 async 方法的新方法。它将 return 完成的任务,在 awaited 时,不会 切换上下文并将同步执行。

在其他情况下,它将使用默认实现,它简单地调用 BeginEndReadAsync - 提供异步模型的旧方法,BeginRead/EndRead 方法对与回调模型.

what is the use of the task here?

base Stream type predated the TAP。当异步方法被添加到 BCL 时,流是一个显而易见的选择(异步代码是 I/O 操作的理想选择)。因此,决定将 ReadAsync(和朋友)添加到基础 Stream 类型中。

但是,必须优先考虑向后兼容性(一如既往)。因此,基础 Stream class 必须包含一个实现;不可能是 abstract。基数 Stream class 将 wrap the BeginRead/EndRead methods (if the derived type implements the APM), or just call Read on a thread pool thread.

MemoryStream - 因为它知道它只是在处理内存缓冲区 - overrides this default thread pool behavior to just be synchronous.