present code is currently structured as follows:
System.Timers.Timer myTimer;
public void FirstMethod() {
myTimer;= new System.Timers.Timer();
myTimer.start();
SecondMethod();
}
public void SecondMethod(){
//several things happen here and then
myTimer.stop();
}
I’ve been advised that I could use using to correctly garbage collect the Timer object. So I’ve tried to apply something like the following to my code (taken from here):
using (SomeClass someClass = new SomeClass())
{
someClass.DoSomething();
}
I assume the following will error because myTimer is not known by SecondMethod()?
public void FirstMethod() {
using (System.Timers.Timer myTimer = new System.Timers.Timer())
{
myTimer.start();
SecondMethod();
}
}
public void SecondMethod(){
//several things happen here and then
myTimer.stop();
}
You wrap an object that implements the
IDisposableinterface in ausingblock when it makes sense to do so. In this case it does not because the object must be valid at a higher scope. Remember, ausingstatement is just shorthand (syntactic sugar) for this:In your case you need to ensure that you call
Dispose()on the object when you are done with it (and in a manner that accounts for exceptions which may be thrown that would prevent the call toDispose()from taking place). You need theTimerto stick around for a while, so ausingblock is out of the question.