local variables in an event Handling method and garbage collection

主宰稳场 提交于 2020-02-05 04:12:27

问题


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();
 }

}
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


回答1:


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.

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.

This means that you can't be certain when SomeClass is getting freed unless you call for the collection yourself.

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



来源:https://stackoverflow.com/questions/59564071/local-variables-in-an-event-handling-method-and-garbage-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!