事件处理方法和垃圾回收中的局部变量 [英] local variables in an event Handling method and garbage collection
问题描述
我是C#编程的新手,所以请耐心等待,在事件处理模式中有一个我无法理解的概念,这里是事件处理的简单实现
I'm new to c# programming so bear with me, there is a concept I couldn't understand in the event handling pattern, here a simple implementation to an event handling
class test
{
someobject.Click += OnClick;
private void OnClick(object sender,EventArgs e)
{
SomeClass someclass = new SomeClass();
}
}
问题是为什么变量someclass
不会被垃圾回收,因为它是OnClick方法中的局部变量,并且在该方法完成时超出范围
}
the problem is why the variable someclass
doesn't get garbage collected since it's a local variable in the method OnClick and gets out of scope when this method finishes
推荐答案
它确实已发布,但不是立即发布.垃圾收集发生在
It does get released, just not right away. Garbage collection occurs when
系统的物理内存不足.可以通过操作系统发出的内存不足通知或主机指示的内存不足来检测到这一点.
The system has low physical memory. This is detected by either the low memory notification from the OS or low memory as indicated by the host.
托管堆上分配的对象使用的内存超过了可接受的阈值.该阈值会随着过程的运行而不断调整.
The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
将调用GC.Collect方法.在几乎所有情况下,您不必调用此方法,因为垃圾收集器会连续运行.此方法主要用于特殊情况和测试.
The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.
这意味着您无法确定何时释放SomeClass
,除非您自己调用该集合.
This means that you can't be certain when SomeClass
is getting freed unless you call for the collection yourself.
来源: https://docs.microsoft.com /en-us/dotnet/standard/garbage-collection/fundamentals
这篇关于事件处理方法和垃圾回收中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!