0

嗨,新来的网站,如果我的问题格式不正确,我深表歉意

如果我有两个事件需要每 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 窗体程序中使用

4

1 回答 1

0

例如,您可以创建一个名为 的类级别 boolIsOn并切换它。您只需要一个计时器来执行此操作,因为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);
}
于 2013-04-13T23:47:42.080 回答