zoukankan      html  css  js  c++  java
  • .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回收。 

  • 相关阅读:
    微信朋友圈分享链接的【图片】设置
    Apache无法访问 Forbidden
    Chrome不能登录和同步的解决方法
    为js和css文件自动添加版本号
    Sqlserver替换函数Replace
    javascript 回车提交指定按钮
    ★★★.NET 在meta标签中使用表达式设置页面的关键字
    es6对象扩展
    es6数组新方法
    es6 字符串
  • 原文地址:https://www.cnblogs.com/csharponworking/p/2002798.html
Copyright © 2011-2022 走看看