我想知道async/await
与垃圾收集局部变量有关的行为。在下面的示例中,我分配了相当大的内存部分并进入了显着延迟。从代码中可以看出,Buffer
在await
. 它会在等待时被垃圾收集,还是在函数执行期间内存被占用?
/// <summary>
/// How does async/await behave in relation to managed memory?
/// </summary>
public async Task<bool> AllocateMemoryAndWaitForAWhile() {
// Allocate a sizable amount of memory.
var Buffer = new byte[32 * 1024 * 1024];
// Show the length of the buffer (to avoid optimization removal).
System.Console.WriteLine(Buffer.Length);
// Await one minute for no apparent reason.
await Task.Delay(60000);
// Did 'Buffer' get freed by the garabage collector while waiting?
return true;
}