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回收。 

  • 相关阅读:
    leetcode hot 100- 84. 柱状图中最大的矩形
    leetcode hot 100- 221. 最大正方形
    leetcode hot 100-34. 在排序数组中查找元素的第一个和最后一个位置
    leetcode hot 100-剑指 Offer 37. 序列化二叉树
    leetcode hot 100-2. 两数相加
    leetcode hot 100-33. 搜索旋转排序数组
    leetcode hot 100- 98. 验证二叉搜索树
    leetcode hot 100-152. 乘积最大子数组
    leetcode hot 100-19. 删除链表的倒数第N个节点
    v-modal的使用。
  • 原文地址:https://www.cnblogs.com/csharponworking/p/2002798.html
Copyright © 2011-2022 走看看