Muhammad Faisal
Muhammad Faisal

Reputation: 155

Abort thread in Elapsed event

Is there any need to abort timer thread in elapsed event? Or will .net do it automatically? Here is my code:

private static void m_checker_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine("[threadid:" + Thread.CurrentThread.ManagedThreadId + "]");
    Thread.CurrentThread.Abort();
}

Upvotes: 1

Views: 56

Answers (1)

hnefatl
hnefatl

Reputation: 6037

No, there's no need (and it could be harmful if it prevents resources from being unallocated). See the MSDN examples here, where they don't do so. This post asks a similar question, and it has some good points in the comments/answers (notably, that the thread the callback runs in is owned by the system).

If you're wanting to stop the timer, then just set its Enabled property to false, eg:

private static void m_checker_Elapsed(object source, ElapsedEventArgs e)
{
    Console.WriteLine("Foo");
    if (condition)
        (source as Timer).Enabled = false;
}

Upvotes: 2

Related Questions