问题
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