Reputation: 1006
I was wondering if using curly brackets to define scopes within a method call would 'force' or give a information to the C# Garbage collector to release the memory allocated within that block, so, let's take the piece of code below as an example:
void MyMethod() {
//here some important code, like reading some information from disk, api, whatever.
//Open brackets to define scope...
{
var myClassObject = new MyClass();
myClassObject.DoSomething();
var mySecondClassObject = new MySecondClass();
mySecondClassObject.DoSomething();
}
//I expect that at this moment, GC would release myClassObject and MySecondClassObject from the Heap...
//is that correct?
//here do something else
/...
}
Upvotes: 2
Views: 324
Reputation: 1870
In Short: No. you are not able to Force the Garbage collector to dispose this allocated !classes! to be disposed right now.
In Long: You might be. You can simply set the variables to Null
and call GC.Collect()
. This will invoke the normal GC collection and Can include the previous unreferenced classes in its collection but there is no Garantie that this will happen. But this will invoke the GarbageCollector for your Whole application not just this thread. This is by design not possible.
Upvotes: 2