I have these codes that use System.Timers.Timer
on a method that called by a Thread
:
private void timeWorker()
{
var timer = new Timer(1000);
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
public MyConstructor()
{
var thread=new Thread(timeWorker);
thread.IsBackground = true;
thread.Start();
//
thread.Abort();
}
Does System.Timers.Timer
terminates on aborting its working Thread?
- You cannot kill timer by aborting thread.
Timer
has its own thread to invoke your event handler.
- Also, as @Damien_The_Unbeliever said timer doesn't belong to any thread, it's system object.
GC
will not collect timer because of your event handler.
You should use try-catch in your thread method implementation, to catch ThreadAbortException
and stop timer.
MSDN C# Threading
I suggest this link for general working with threads. It is also mentioned that Abort
will interrupt the Thread and prevents used ressources to be cleaned up.
A better option would be a method to call that disables the while-loop inside the timeWorker
Class like
public void RequestStop()
{
running = false;
}
while the worker is doing his work in the loop
public void DoWork()
{
while(running)
{
...
}
//execution stopped
}
with a variable private volatile bool running
.