• C#简单使用System.Threading.Timer


    直接上代码。

     1 using System;
     2 using System.Threading;
     3 
     4 namespace DevicePowerManager.Tools
     5 {
     6     public class TestTimer
     7     {
     8         /// <summary>
     9         /// 用于指定无限期等待一段时间,.Net 4.5及以上可以使用Timeout.InfiniteTimeSpan
    10         /// </summary>
    11         private static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1);
    12 
    13         private readonly Timer _timer;
    14 
    15         public TestTimer()
    16         {
    17             //创建定时器
    18             _timer = new Timer(TimerFunc, null, InfiniteTimeSpan, InfiniteTimeSpan);
    19         }
    20 
    21         public void Start()
    22         {
    23             //启动定时器
    24             _timer.Change(TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(300));
    25         }
    26 
    27         public void Stop()
    28         {
    29             //停止计时器
    30             _timer?.Change(InfiniteTimeSpan, InfiniteTimeSpan);
    31         }
    32 
    33         private void TimerFunc(object state)
    34         {
    35 
    36         }
    37     }
    38 }

    确定不再使用Timer时,可以使用Dispose释放资源。

    _timer?.Dispose();
  • 相关阅读:
    BOZJ2200: [Usaco2011 Jan]道路和航线
    poj3662
    网络流
    最短路
    约瑟夫环
    二分图匹配
    HDU 3938 Portal
    背包dp专题训练
    noip2013day1模拟赛
    2017.10.24:lca专题系列
  • 原文地址:https://www.cnblogs.com/xhubobo/p/14451345.html
Copyright © 2020-2023  润新知