jeffbeat
jeffbeat

Reputation: 69

using statement - does it trigger garbage collection?

What I'd like to do is wrap some suspect functions that may be leaking in a using statement to trigger garbage collection, has anyone used or seen something like this? Does this work? Whats your thoughts on this?

using (String wrapper = new String("maybe this will trigger gc")){
  //do stuff here
  //or maybe:
  // function1();
  // function2();
  //
  //and then see if its leaking?

  // eg:
       _mygeometry = new Geometry();
       _mygeometry = null; // will GC free this ?
}

Do you think this will work? Have you used this before? Is there something I can do that isnt a String? Im using WPF, I tried using ( var garbage = 1 ){} and doesnt work, I suppose String might though.

Upvotes: 0

Views: 3938

Answers (2)

Habib
Habib

Reputation: 223287

using statement only works for those classes which implements IDisposable. It just makes sure that the object you defined inside the using() will call its Dispose method after the execution of the block or even when some exception occurs. It is just similar to using try with finally block.

If you are suspecting memory leakage in your application then its better if you use some of the available memory profilers to detect the problem.

Your current code shouldn't compile as String class doesn't implement IDisposable

EDIT:

Since the edited question

_mygeometry = null; // will GC free this ?

You should see this SO Link: C#: should object variables be assigned to null? and answer from VinayC

Upvotes: 7

Andre Calil
Andre Calil

Reputation: 7692

Only classes that implement IDisposable can be used within using(...){...} statements.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

Source: MSDN

Unfortunately, string does not implement this interface. Are you suspecting that a string is causing memory leak at your app? What are you processing? Could you post some code so we'd be able to inspect it?

Upvotes: 2

Related Questions