是什么使委托多目标对象保留在范围内?
是什么使 t
成为根引用(留在范围内)? (t
是一个用户定义的类)
我在IL间谍中查看,它不是一个常见的捕获变量!
Action runs = null;
while (dummy <= tod.Value.Date)
{
var t = new Task(dummy, _interval);
runs += t.Run;
dummy = dummy.AddDays(1);
}
GC.Collect();
((Action)(() => { runs(); })).BeginInvoke(Result, null);
有人可以向我解释一下吗? t(任务)类如何保持在范围内,是什么让它扎根,我猜它是运行委托,但是如何呢?
What makes t
a rooted reference (stay in scope) ? (t
is a user defined class)
I look at in in IL spy, and its not a common capture variable !
Action runs = null;
while (dummy <= tod.Value.Date)
{
var t = new Task(dummy, _interval);
runs += t.Run;
dummy = dummy.AddDays(1);
}
GC.Collect();
((Action)(() => { runs(); })).BeginInvoke(Result, null);
Can someone explain this to me? How the t
(task) classes stay in scope, what makes it rooted, I guess its the runs delegate, but how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我应该指出,这与范围没有太大关系,范围是程序文本的区域,在该区域中可以使用实体的简单名称来引用实体。这是关于可达性。
现在我还没有使用内存分析器查看相关堆,但是Task
对象的路径看起来像这样:Action(多播)委托实例是 GC 根,因为它由
runs
(本地)引用。_invocablelist
字段保持其各个订阅者的活动状态,该字段保存对委托数组的引用。Action
委托实例的引用。_target
字段(它将充当传递给this
的引用) code>Task.Run 方法(当调用委托时)。该字段将保存对Task
实例的引用。总结一下:
更新:
我通过Ants Memory Profiler,证实了我的想法:
Firstly, I should point out that this doesn't have much to with scope, which is the region of program text in which one can refer to an entity using its simple name. It's about reachability.
Now I haven't looked at the heap in question with a memory profiler, but the path to aTask
object would look something like this:Action
(multicast) delegate instance is a GC root since it is referenced byruns
(a local)._invocationlist
field, which holds a reference to a delegate array.Action
delegate instances._target
field (which will act as thethis
reference passed to theTask.Run
method when the delegate is invoked). This field will hold a reference to theTask
instance.To summarize:
UPDATE:
I ran this through Ants Memory Profiler, which confirmed my thoughts: