while 循环中一次性变量的范围何时结束?
When does the scope of a disposable variable in a while loop end?
我有一个 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);
}
}
我的问题是:memoryStream
会在每次迭代中还是在循环结束时被处理掉?
虽然问题 大致回答了这个主题,但它没有明确回答有关 while 循环中一次性变量范围的问题。
内存流将在 while
循环块的末尾处理,因此每 while
循环迭代一次。
这就是您的代码将如何执行(我已经简化了您的方法以仅包含必要的部分):
public void CaptureImages(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
MemoryStream memoryStream = new MemoryStream();
try
{
}
finally
{
if (memoryStream != null)
{
((IDisposable)memoryStream).Dispose();
}
}
}
}
如您所见,memoryStream
将在每次迭代中被释放。您可以在 SharpLap.
中找到代码编译的中间步骤和结果。
是正确的,但我想扩展一点来解释为什么它是正确的:
这实际上是一个关于c#8 using declaration的问题:
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
基本上,using
声明被编译为 using
语句,它在封闭范围结束之前结束。
换句话说,您的代码被翻译成这样:
while(!ct.IsCancellationRequested)
{
await using(var memoryStream = new MemoryStream())
{
await this.camera.CaptureImage(memoryStream, ct);
await this.storage.StoreImage(memoryStream, ct);
}
}
现在,当 memoryStream
被处置时,这一点非常清楚 - 在每个 while
迭代结束时。
我有一个 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);
}
}
我的问题是:memoryStream
会在每次迭代中还是在循环结束时被处理掉?
虽然问题
内存流将在 while
循环块的末尾处理,因此每 while
循环迭代一次。
这就是您的代码将如何执行(我已经简化了您的方法以仅包含必要的部分):
public void CaptureImages(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
MemoryStream memoryStream = new MemoryStream();
try
{
}
finally
{
if (memoryStream != null)
{
((IDisposable)memoryStream).Dispose();
}
}
}
}
如您所见,memoryStream
将在每次迭代中被释放。您可以在 SharpLap.
这实际上是一个关于c#8 using declaration的问题:
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
基本上,using
声明被编译为 using
语句,它在封闭范围结束之前结束。
换句话说,您的代码被翻译成这样:
while(!ct.IsCancellationRequested)
{
await using(var memoryStream = new MemoryStream())
{
await this.camera.CaptureImage(memoryStream, ct);
await this.storage.StoreImage(memoryStream, ct);
}
}
现在,当 memoryStream
被处置时,这一点非常清楚 - 在每个 while
迭代结束时。