gpt4 book ai didi

c# - .NET lambda 是否会阻止对其中使用的外部引用进行垃圾回收?

转载 作者:太空狗 更新时间:2023-10-29 22:11:56 26 4
gpt4 key购买 nike

这是一个例子:

var task = Task.Run();
var func = () => task.Result;

因此,如果我松开任务引用并保留函数引用,GC 是否会收集任务并使函数抛出空引用异常?

最佳答案

没有。匿名函数捕获变量,将其生命周期至少延长到委托(delegate)或表达式树被垃圾回收时。

来自 C# 5 规范,第 7.15.5.1 节:

When an outer variable is referenced by an anonymous function, the outer variable is said to have been captured by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated (§5.1.7). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.

请注意,捕获的是变量,而不是当时变量的值。因此,如果您将代码更改为:

var task = Task.Run(...);
var func = () => task.Result;
task = null;

...那么原始的 Task 可以被垃圾回收,如果你调用它,委托(delegate)会抛出异常,因为它会使用 current task 变量的值。

关于c# - .NET lambda 是否会阻止对其中使用的外部引用进行垃圾回收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31729665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com