while 循环中一次性变量的作用域何时结束?

Spo*_*xus 1 .net c# scope .net-core

我有一个 while 循环,其中我用内存流做一些事情 - 即将它传递给填充流或从中读取的其他对象。代码如下所示:

public async void CaptureImages(CancellationToken ct)
{
    while(!ct.IsCancellationRequested)
    {
        await using var memoryStream = new MemoryStream();

        await this.camera.CaptureImage(memoryStream, ct);
        await this.storage.StoreImage(memoryStream, ct);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:将memoryStream在每次迭代或循环结束后处理?

虽然问题C# 8 Using Declaration Scope Confusion一般性地回答了这个主题,但它没有明确回答有关 while 循环中一次性变量的范围的问题。

Sea*_*ean 5

内存流将被放置在while循环块的末尾,因此每次while循环迭代一次。


Zoh*_*led 5

肖恩的答案是正确的,但我想扩展一点来解释为什么它是正确的:

这实际上是一个关于c#8 using 声明的问题:

using 声明是前面带有 using 关键字的变量声明。它告诉编译器声明的变量应该被放置在封闭范围的末尾。

基本上,using声明被编译为using语句,在封闭范围结束之前结束。换句话说,你的代码被翻译成这样:

while(!ct.IsCancellationRequested)
{
    await using(var memoryStream = new MemoryStream())
    {
        await this.camera.CaptureImage(memoryStream, ct);
        await this.storage.StoreImage(memoryStream, ct);
    }
}
Run Code Online (Sandbox Code Playgroud)

memoryStream现在,当每次迭代结束时处理时,这一点非常清楚while