ghostJago
ghostJago

Reputation: 3434

System.Diagnostics.TraceListener explicit Dispose() in foreach loop object?

I have code similar to the following, should I explicity dispose of the listener object in the following code?

i.e should this code:

foreach (System.Diagnostics.TraceListener listener in localObj.Listeners)
    listener.WriteLine("some logging");

be re-written as:

foreach (System.Diagnostics.TraceListener listener in localObj.Listeners)
{
    listener.WriteLine("some logging");
    listener.Dispose();
}

reasons for either way of coding would be appreciated.

Upvotes: 0

Views: 298

Answers (2)

nbulba
nbulba

Reputation: 645

Sorry, I would like to comment on the ChrisBint answers, but I couldn't. In brief, I agree with ChrisBint, you should not call Dispose in the above-mentioned scenario:

  1. TraceListeners belong to localObj, and it is responsibility of the localObj to rule the lifetime of its inetrnal objects. Therefore the second piece of code seems odd enough.
  2. If you implement getter of localObj.Listeners with generation of new collection and do not expose real internals of the localObj, you needn't explicitly call Dispose, it will be called by the GarbageCollector.

Upvotes: 1

Kinexus
Kinexus

Reputation: 12904

In the above code, you are just accessing a reference to each TraceListener and calling the WriteLine() Method and there is no need to call Dispose() in this scenario.

Upvotes: 3

Related Questions