使用System.Timers.Timer实现协同

来源:互联网 发布:淘宝汽车饰品名字 编辑:程序博客网 时间:2024/05/17 09:30
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;

namespace ThreadSynchronization
{
    class Program
    {
        #region

        static List<int> list = new List<int>();
        public static void write1(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("111111");
        }

        public static void write2(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("222");
        }
        #endregion

        
        static void Main(string[] args)

        {

           //方法write1在间隔100秒后执行

            System.Timers.Timer t = new System.Timers.Timer(100);                  //设置方法执行的时间间隔

            t.Elapsed += new System.Timers.ElapsedEventHandler(write1);      //时间间隔到时要执行的方法


            t.AutoReset = true;                       //该方法是一直执行还是执行一次后就停止,false为执行一次就停止,true为不停的执行
            t.Enabled = true;                            //是否执行Elapsed的方法

            System.Timers.Timer t2 = new System.Timers.Timer(200);
            t2.Elapsed += new System.Timers.ElapsedEventHandler(write2);
            t2.AutoReset = true;
            t2.Enabled = true;

            Console.ReadLine();
        }
    }
}