在调用事件时使用Thread.Sleep,但不起作用?(C#)

时间:2016-07-03 13:03:41

标签: c# multithreading

大家: 我最近使用“Illustrated C#2010”**来学习csharp,我刚刚来到第16章“事件”。 **其中有一个示例,我运行原始代码但得到的结果不同。我真的很困惑!以下是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace EventSample1
{
    public class MyTimerClass
    {
        public event EventHandler MyElapsed; 
        private void OnOneSecond(object source, EventArgs args)
        {
            if(MyElapsed != null)
                MyElapsed(source, args);
        }
        //----
        private System.Timers.Timer MyPrivateTimer; 
        public MyTimerClass()
        {
            MyPrivateTimer = new System.Timers.Timer(); 
            MyPrivateTimer.Elapsed += OnOneSecond; 
            MyPrivateTimer.Interval = 1000;               
            MyPrivateTimer.Enabled = true;
        }
    }
    //----
    class classA
    {
        public void TimerHandlerA(object source, EventArgs args)
        {
            Console.WriteLine("class A handler called!");
        }
    }
    class classB
    {
        public static void TimerHandlerB(object source, EventArgs args)
        {
            Console.WriteLine("class B handler called!");
        }
    }
    //-----
    class Program
    {
        static void Main()
        {
            classA ca = new classA();
            MyTimerClass mc = new MyTimerClass();
            //----
            mc.MyElapsed += ca.TimerHandlerA;
            mc.MyElapsed += classB.TimerHandlerB;
            //----
            Thread.Sleep(2250);
            Console.ReadLine();
        }
    }
}

这本书说我们会让TimerHandler A和B都执行两次,而线程睡眠时间为2.25秒。并且屏幕上应该有4行。 像这样:

>>class A handler called!
>>class B handler called!
>>class A handler called!
>>class B handler called!

但在我运行代码之后,TimerHandler A和B被永远调用,超过2次。喜欢这样:

>>class A handler called!
>>class B handler called!
>>class A handler called!
>>class B handler called!
>>class A handler called!
>>class B handler called!
>>class A handler called!
>>class B handler called!
......

我猜使用thread.sleep时出现了问题,但我还没有在C#中学过任何关于线程的内容......在书中,我们没有解释为什么要使用thread.sleep,以及为什么使用它会控制事件只执行两次。

有人可以解释一下吗?这本书是错误的吗?或者我有什么问题? 我在XP上使用vs2010。

谢谢!

1 个答案:

答案 0 :(得分:2)

程序有Console.ReadLine(),它会一直等到你按下Return键。当它正在等待时,计时器仍在运行,因此将触发事件。在这种情况下,Thread.Sleep毫无意义。

我希望作者的目的是在看到结果之前阻止Console应用程序退出和消失。

如果您注释掉ReadLine(),程序将按照书中所述进行操作,但应用程序将在2.25秒后立即退出并消失,因此请密切关注屏幕以查看效果。