Does System.Timers.Timer terminates on aborting it

2019-08-03 10:03发布

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?

2条回答
Summer. ? 凉城
2楼-- · 2019-08-03 10:36

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.

查看更多
一夜七次
3楼-- · 2019-08-03 10:44
  1. You cannot kill timer by aborting thread.
  2. Timer has its own thread to invoke your event handler.
  3. Also, as @Damien_The_Unbeliever said timer doesn't belong to any thread, it's system object.
  4. 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.

查看更多
登录 后发表回答