本文介绍了System.Threading.Timer类,它是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制台应用程序中有以下代码。

现在如果我运行它显示'11 / 11/2013'作为输出。

但是如果我发表评论行没有。 9(System.Threading.Thread.Sleep(1000);)相同的程序什么都没显示。根据我的知识,应该调用TimerTask()。

为什么它依赖于'System.Threading.Thread.Sleep(1000)'来调用TimerTask()。



I have following code in console application.
Now if i run it shows '11/11/2013' as output.
But if i make comment line no. 9 (System.Threading.Thread.Sleep(1000);) the same program shows nothing. As per my knowledge TimerTask() should have been called.
Why it depends on 'System.Threading.Thread.Sleep(1000)' for calling TimerTask().

class Program
    {
        static void Main(string[] args)
        {
 System.Threading.TimerCallback TimerDelegate =
                new System.Threading.TimerCallback(TimerTask);
System.Threading.Timer TimerItem =
                new System.Threading.Timer(TimerDelegate, null, 0, 2000);
System.Threading.Thread.Sleep(1000);
}
 private static void TimerTask(object StateObj)
        {
           Console.WriteLine(DateTime.Now.ToString());
}

推荐答案


class Program
    {
        static void Main(string[] args)
        {
            System.Threading.TimerCallback TimerDelegate =
                new System.Threading.TimerCallback(TimerTask);
            System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, null, 1, 4000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
            System.Threading.Thread.Sleep(1000);
        }

        private static void TimerTask(object StateObj)
        {
            Console.WriteLine(DateTime.Now.ToString());
        }
    }





它会显示结果



注意:您的程序将在最后执行Thread.Sleep时关闭



it will show result

NOTE:your program will close as the last "Thread.Sleep" would be executed


这篇关于System.Threading.Timer类,它是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 11:01