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

  • 相关阅读:
    01-文件系统
    适配器模式,新老系统兼容
    01-Entity FrameWork如何控制数据的变化
    .Net实战之反射操作篇
    .Net实战之反射相关类之间的人体经络关系
    .Net实战之反射外卖计费
    [转]UINavigationController 返回的方法汇总
    [转]AFNetWorking使用笔记
    vue----子组件引用vux popup mask遮罩在最上层解决办法 z-index问题
    vue系列---vue项目(已安装vuex)中引入jquery
  • 原文地址:https://www.cnblogs.com/csharponworking/p/2002798.html
Copyright © 2011-2022 走看看