事件处理方法和垃圾收集中的局部变量

local variables in an event Handling method and garbage collection

我是 c# 编程的新手,所以请耐心等待,在事件处理模式中有一个我无法理解的概念,这里是事件处理的简单实现

class test
{
 someobject.Click += OnClick;
 private void OnClick(object sender,EventArgs e)
 {
   SomeClass someclass = new SomeClass();
 }

}
问题是为什么变量 someclass 没有被垃圾收集,因为它是方法 OnClick 中的 局部变量 并且在此方法完成时超出范围

它确实被释放了,只是不是马上。垃圾收集发生在

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.

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 何时被释放,除非您自己要求收集。

来源:https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals