Consider the following method:
DoTimeIntensiveOperation()
{
var t = new Stopwatch();
foreach(var element in a_very_long_array)
{
DoATimeConsumingTask(element);
}
Console.WriteLine("Took me " + t.Elapsed);
return;
}
Do I need to call t.Stop()
before returning?
As far as I know, the garbage collector will destroy anything that doesn't have a reference chain going back to the main method. The only reference to the created Stopwatch
is t
, so when DoTimeIntensiveOperation
, t
will be freed and the Stopwatch
should be eligible for destruction. But does the fact that it's still "ticking" interfere with the GC?
No, there is no need to stop or clean it up. Stopwatch does not use any unmanaged resources (if you thought of IDisposable ). It actually does not use any resources at all (except the memory used by the object itself, of course)! It also does not consume any CPU while measuring the elapsed time!
You can either cancel the entire Timer by calling Timer. cancel() , or you can cancel individual tasks by calling TimerTask. cancel() .
No, I threw this quick test and it seems that once the GC is run, the stopwatch is destroyed. (Feel free to correct the code)
static void Main(string[] args)
{
DoTimeIntensiveOperation();
GC.Collect();
while (swRef.IsAlive)
{
}
Console.WriteLine("Destroyed");
}
static WeakReference swRef = null;
static void DoTimeIntensiveOperation()
{
Stopwatch sw = new Stopwatch();
sw.Start();
swRef = new WeakReference(sw);
return;
}
The output is Destroyed
when GC.Collect
is called. Of course, in a real program you're unlikely to explicitly call GC.Collect
but this is to show that the Stopwatch object is destroyed once out the scope of the method even if Stop
hasn't been called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With