habib
habib

Reputation: 2446

Should I need to dispose System.Threading.Timer after completing my task?

I'm using this code to execute my code once with the 10-second delay on a separate thread.

System.Threading.Timer timer = null;
timer = new System.Threading.Timer(e=> {
    //My code
    timer.Dispose();
    },null,10000,System.Threading.Timeout.Infinite);  

I want to ask that if I need to use timer.Dispose() after completing my task or the timer will be released automatically.

Upvotes: 1

Views: 1015

Answers (1)

Bruno Caceiro
Bruno Caceiro

Reputation: 7189

Yes you should always dispose the Timer.

From the docs:

When a timer is no longer needed, use the Dispose method to free the resources held by the timer. Note that callbacks can occur after the Dispose() method overload has been called, because the timer queues callbacks for execution by thread pool threads. You can use the Dispose(WaitHandle) method overload to wait until all callbacks have completed.

Upvotes: 2

Related Questions