偏移计时器启动

时间:2013-04-13 23:18:05

标签: c#

您是网站的新手,所以如果我的问题格式不正确,我会道歉

如果我有两个事件需要每2秒交替一次(一个是ON而另一个是OFF),我怎样才能延迟其中一个定时器的起始为2秒的偏移?

    static void Main(string[] args)
    {

        Timer aTimer = new Timer();
        Timer bTimer = new Timer();

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        bTimer.Elapsed += new ElapsedEventHandler(OnTimedEventb);

        // Set the Interval to 4 seconds 
        aTimer.Interval = 4000;
        aTimer.Enabled = true;
        bTimer.Interval = 4000;
        bTimer.Enabled = true;


        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();
    }
    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The status is on {0}", e.SignalTime);
    }
    private static void OnTimedEventb(object source, ElapsedEventArgs b)
    {
        Console.WriteLine("The state is off {0}", b.SignalTime);
    }

所以我基本上希望在程序启动时发生ON事件,然后在2秒后发生OFF事件,等等

使用vs 2012控制台应用程序,但我将在Windows窗体程序中使用

1 个答案:

答案 0 :(得分:0)

例如,您可以创建名为IsOn的班级水平书,然后切换。您只需要一个计时器就可以执行此操作,因为true表示它已启用,false表示它已关闭。

private static bool IsOn = true; //default to true (is on)
static void Main(string[] args)
{

    Timer aTimer = new Timer();


    // Hook up the Elapsed event for the timer.
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);        

    // Set the Interval to 2 seconds 
    aTimer.Interval = 2000;
    aTimer.Enabled = true;    


    Console.WriteLine("Press the Enter key to exit the program.");
    Console.ReadLine();
}


// Specify what you want to happen when the Elapsed event is  
// raised. 
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    IsOn = !IsOn;
    Console.WriteLine("The status is {0} {1}", IsOn.ToString(), e.SignalTime);
}