使用两个System.Threading.Timers

时间:2014-04-08 18:01:14

标签: c# timer

我需要在两个不同的主题中使用2个计时器,但它似乎无法正常工作。

我已经在控制台上试过了,我得到了这个结果:http://puu.sh/810Ki.png

代码:

    static void Main(string[] args)
    {
        Thread thread1 = new Thread(Start1);
        thread1.Start();

        Thread thread2 = new Thread(Start2);
        thread2.Start();

        Console.ReadLine();
    }

    private static void Start1()
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + " Begin System.Threading.Timer1.");

        Timer timerThread = new Timer(TimerConnectionThread_Finished1, null, 10000, Timeout.Infinite);
    }

    private static void Start2()
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + " Begin System.Threading.Timer2.");

        Timer timerThread2 = new Timer(TimerConnectionThread_Finished2, null, 10000, Timeout.Infinite);
    }

    private static void TimerConnectionThread_Finished1(object stateInfo)
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + " End System.Threading.Timer1.");
        Console.WriteLine(DateTime.Now.ToLongTimeString() + " Begin System.Threading.Timer1.");
        Timer timerThread = new Timer(TimerConnectionThread_Finished1, null, 10000, Timeout.Infinite);
    }

    private static void TimerConnectionThread_Finished2(object stateInfo)
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + " End System.Threading.Timer2.");
        Console.WriteLine(DateTime.Now.ToLongTimeString() + " Begin System.Threading.Timer2.");
        Timer timerThread = new Timer(TimerConnectionThread_Finished2, null, 10000, Timeout.Infinite);
    }

我们可以看到Timer1和Timer2切换。我该怎么办 ?使用System.Timers.Time?编码我自己的计时器?

谢谢,

Veriditas:)

0 个答案:

没有答案