M
Mark
Hi
This is a fairly generic question about programming style and to a certain
extent garbage collection. I have some methods that I write to text logs,
the event log etc at various places in the method. What I do is open the
various logs at the start of the method and, being good, I explicitly close
them at the end. In the method, I also catch exceptions at various places.
For some of these exceptions, I wish to exit the method. Now being pedantic,
I also want to close the logs before exiting the method even in the catch
clause. So what I end up with is something like:
private void myMethod()
{
EventLog log = new EventLog(strMyLog);
log.Source = strMySource;
// main block of code here, followed by...
try
{
// some code that might throw an exception
}
catch
{
// some exception code here
log.Dispose();
return;
}
// bit mode code to do stuff here
try
{
// some more code that might throw an exception
}
catch
{
// more exception code here
log.Dispose();
return;
}
// final code stuff here
log.Dispose();
}
Whilst this works and forces me to do all the tidying up myself, it appears
a bit clunky. So my question is:
- Should I just not bother trying to tidy up and just let the garbage
collector sort everything out? (This goes against the grain!)
- Is there a better way of organizing the code so that I only have one
log.Dispose()?
- Perhaps I should wrap the whole method in a try finally clause? (This
seems a weird option.)
- Am I just worrying about nothing?
TIA
Mark
This is a fairly generic question about programming style and to a certain
extent garbage collection. I have some methods that I write to text logs,
the event log etc at various places in the method. What I do is open the
various logs at the start of the method and, being good, I explicitly close
them at the end. In the method, I also catch exceptions at various places.
For some of these exceptions, I wish to exit the method. Now being pedantic,
I also want to close the logs before exiting the method even in the catch
clause. So what I end up with is something like:
private void myMethod()
{
EventLog log = new EventLog(strMyLog);
log.Source = strMySource;
// main block of code here, followed by...
try
{
// some code that might throw an exception
}
catch
{
// some exception code here
log.Dispose();
return;
}
// bit mode code to do stuff here
try
{
// some more code that might throw an exception
}
catch
{
// more exception code here
log.Dispose();
return;
}
// final code stuff here
log.Dispose();
}
Whilst this works and forces me to do all the tidying up myself, it appears
a bit clunky. So my question is:
- Should I just not bother trying to tidy up and just let the garbage
collector sort everything out? (This goes against the grain!)
- Is there a better way of organizing the code so that I only have one
log.Dispose()?
- Perhaps I should wrap the whole method in a try finally clause? (This
seems a weird option.)
- Am I just worrying about nothing?
TIA
Mark