c# 高级编程 21章475页 【任务和并行编程】【Timer类】

102 阅读1分钟

Timer类

使用计时器,可以重复调用方法 两个计时器:

  1. System.Threading命名空间中的Timer
  2. 基于XAML应用程序的DispatcherTimer

System.Threading.Timer

构造函数接收4个参数

  1. 要调用的方法:TimeCallback委托类型(入参object, 返回void
  2. 任意对象。该对象会传给1中的方法
    • 可以传递null,如下例
  3. 第一次调用1方法的时间
  4. 重复调用1方法的时间间隔
    • 如果只调用一次, 可以设为-1
    class Program
    {
        static void Main(string[] args)
        {
            ThreadingTimer();
        }

        private static void ThreadingTimer()
        {
            void TimeAction(object o)
            {
                Console.WriteLine($"System.Threading.Timer {DateTime.Now:T}");
            }

            using (var t1 = new Timer(
               TimeAction, null, TimeSpan.FromSeconds(2),
               TimeSpan.FromSeconds(3)))
            {

                Task.Delay(15000).Wait();
            }
        }
    }

DispatcherTimer

  • 基于XAML应用程序
  • 其中的事件处理程序在UI线程中调用,因此可以直接访问UI元素