.net 线程中的timer 的思考

最近在项目中用到线程的timer 即Systetm.Threading.Timer 类。下面是简单的实例。
using System.Threading;
using System;
public class Sample
{
    
public static void Main()
    {
        TestException test
=new TestException();
        test.Start();
        Console.Read();
    }

}

public class TestException
{
    
private Timer workerTimer;
    
private TimerCallback timerCallback;

    
public TestException()
    {
        timerCallback
=new TimerCallback(Working);
        workerTimer
=new Timer(timerCallback,null,Timeout.Infinite,Timeout.Infinite);
    }
    
    
public void Start()
    {
        workerTimer.Change(
2000,2000);
    }
    
    
public void Stop()
    {
        workerTimer.Change(Timeout.Infinite,Timeout.Infinite);
    }

    
///此方法抛出异常
    private void WorkMethod()
    {

        
//Console.WriteLine("执行了");
        throw new Exception("我自己抛出的异常");
    }

    
private void Working(object state)
    {
        
try
        {
            
//先停止timer ,在启动timer
            workerTimer.Change(Timeout.Infinite,Timeout.Infinite);
            Console.WriteLine(
"执行了");
            WorkMethod();
        }
catch(Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        
finally
        {
            workerTimer.Change(
2000,2000);
        }
    }

} 

以上代码是简单的使用方法。但是有几点需要注意的
1.Timer 执行的方法内部,如果抛出异常了,则timer 就不执行了。所以,如上,在方法里把异常处理了。这样timer 就可以正常执行。

2.关于Timer  的gc ,就是如果timer 不被调用,则会被gc回收。 

原文地址:https://www.cnblogs.com/csharponworking/p/2002798.html