先打开一个定时器,循环对串口发出代码。当有事件来时暂停定时器,事件结束后再启动定时器。也就是事件执行的过程中挂起定时器。请问大侠们如何挂起定时器。我使用的是 System.Timers.Timer Timer9= new System.Timers.Timer();中的定时器。

解决方案 »

  1.   

    Timer9.Start() 开始引发 Elapsed 事件。
    Timer9.Stop()  停止引发 Elapsed 事件。 
      

  2.   

    那如果TIMER9里的代码执行到一半, timer9.stop()停止引发会不会立即挂起定时器?
      

  3.   

    那如果TIMER9里的代码执行到一半, timer9.stop()停止引发会不会立即挂起定时器?
      

  4.   


    stop()不能说是挂起定时器,只能停止定时器引发Elapsed事件,不会中断触发事件里已开始执行的代码。
      

  5.   

    其实你的问题应该是个多线程同步的问题,你可以参考下网上有的线程同步的资料。
    如果我会用以下方法处理,可能效率不高,见笑了。public class Timer1
    {
        // 标记串口是否被占用
        bool m_bIsOccu = false;    // 定时器
        System.Timers.Timer aTimer;    public static void Main()
        {
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);        aTimer.Interval = 2000;
            aTimer.Enabled = true;
     
            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();        // Keep the timer alive until the end of Main.
            GC.KeepAlive(aTimer);
        }
     
        // 定时器对串口发出代码函数
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            // 标记串口被占用
            m_bIsOccu = true;        // 替换为你自己的发送代码
            Console.WriteLine("Hello World!");        // 恢复串口标记
             m_bIsOccu = false;
        }    private void OtherEvent()
        {
            // 停止定时器
            aTimer.Stop();
            
            // 等待串口资源释放
             while(m_bIsOccu)
            {
                 Thread.Sleep(100);
            }        // 你的事件处理函数
            ....        // 重新启动定时器
             aTimer.Start();
        }
    }
      

  6.   

    鄙人觉得如果只是线程同步的问题的话,不用挂起timer,用互斥锁就OK了public class Timer1
    {
        // 标记串口是否被占用
        bool m_bIsOccu = false;    // 定时器
        System.Timers.Timer aTimer;    // 锁
        object theLock = new object();    public static void Main()
        {
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);        aTimer.Interval = 2000;
            aTimer.Enabled = true;
     
            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();        // Keep the timer alive until the end of Main.
            GC.KeepAlive(aTimer);
        }
     
        // 定时器对串口发出代码函数
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            lock(theLock)
            {
                // 替换为您自己的发送代码
                Console.WriteLine("Hello World!");
            }
            
        }    private void OtherEvent()
        {
            lock(theLock)
            {                   // 您的事件处理函数
                 ....
            }
        }