简体   繁体   English

System.Threading.Timer是否实际上在两个不同的线程中运行?

[英]Does System.Threading.Timer actually run in two different threads?

The code sample below 下面的代码示例

using System.Threading;

namespace TimerApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Timer Application *****\n");
            Console.WriteLine("In the thread #{0}",     Thread.CurrentThread.ManagedThreadId); 

            // Create the delegate for the Timer type. 
            TimerCallback timerCB = new TimerCallback(ShowTime);

            // Establish timer settings. 
            Timer t = new Timer(
                timerCB,                // The TimerCallback delegate object. 
                "Hello from Main()",    // Any info to pass into the called method (null for no info). 
                0,                      // Amount of time to wait before starting (in milliseconds). 
                1000);                  // Interval of time between calls (in milliseconds). 

            Console.WriteLine("Hit key to terminate...");
            Console.ReadLine(); 
        }

        // Method to show current time... 
        public static void ShowTime(object state)
        {
        Console.WriteLine("From the thread #{0}, it is background?{1}: time is {2}, param is {3}", 
            Thread.CurrentThread.ManagedThreadId, 
            Thread.CurrentThread.IsBackground,
            DateTime.Now.ToLongTimeString(), 
            state.ToString()); 
        }
    }
 } 

produces the following output 产生以下输出

***** Timer Application ***** *****计时器应用*****

In the thread #1 在线程#1中
Hit key to terminate... 按下键终止...
From the thread #4, it is background?True: time is 10:37:54 PM, param is Hello from Main() 从线程#4开始,它是背景吗?正确:时间是10:37:54 PM,参数是Main()中的Hello
From the thread #4, it is background?True: time is 10:37:55 PM, param is Hello from Main() 从线程#4开始,它是背景吗?正确:时间是10:37:55 PM,参数是Main()中的Hello
From the thread #5, it is background?True: time is 10:37:56 PM, param is Hello from Main() 从线程#5开始,它是背景吗?正确:时间是10:37:56 PM,参数是Main()中的Hello
From the thread #4, it is background?True: time is 10:37:57 PM, param is Hello from Main() 从线程#4开始,它是背景吗?正确:时间是10:37:57 PM,参数是Main()中的Hello
From the thread #5, it is background?True: time is 10:37:58 PM, param is Hello from Main() 从线程5开始,它是背景吗?是:时间是10:37:58 PM,参数是Main()中的Hello
From the thread #4, it is background?True: time is 10:37:59 PM, param is Hello from Main() 从线程#4开始,它是背景吗?正确:时间是10:37:59 PM,参数是Main()中的Hello
From the thread #5, it is background?True: time is 10:38:00 PM, param is Hello from Main() 从线程#5开始,它是背景吗?是:时间是10:38:00 PM,参数是Main()中的Hello
... ...
Press any key to continue . 按任意键继续 。 . .

Does the System.Threading.Timer make callbacks using several threads at a time? System.Threading.Timer是否一次使用多个线程进行回调?

It makes use of the thread pool, using the first thread that it finds available at each time interval. 它利用线程池,并在每个时间间隔使用发现的第一个线程。 The timer simply triggers the firing of these threads. 计时器只是触发这些线程的触发。

void Main()
{
    System.Threading.Timer timer = new Timer((x) =>
    {
        Console.WriteLine($"{DateTime.Now.TimeOfDay} - Is Thread Pool Thread: {Thread.CurrentThread.IsThreadPoolThread} - Managed Thread Id: {Thread.CurrentThread.ManagedThreadId}");
        Thread.Sleep(5000);

    }, null, 1000, 1000);

    Console.ReadLine();
}

Output 输出量

07:19:44.2628607 - Is Thread Pool Thread: True - Managed Thread Id: 10
07:19:45.2639080 - Is Thread Pool Thread: True - Managed Thread Id: 13
07:19:46.2644998 - Is Thread Pool Thread: True - Managed Thread Id: 9
07:19:47.2649563 - Is Thread Pool Thread: True - Managed Thread Id: 8
07:19:48.2660500 - Is Thread Pool Thread: True - Managed Thread Id: 12
07:19:49.2664012 - Is Thread Pool Thread: True - Managed Thread Id: 14
07:19:50.2669635 - Is Thread Pool Thread: True - Managed Thread Id: 15
07:19:51.2679269 - Is Thread Pool Thread: True - Managed Thread Id: 10
07:19:52.2684307 - Is Thread Pool Thread: True - Managed Thread Id: 9
07:19:53.2693090 - Is Thread Pool Thread: True - Managed Thread Id: 13
07:19:54.2839838 - Is Thread Pool Thread: True - Managed Thread Id: 8
07:19:55.2844800 - Is Thread Pool Thread: True - Managed Thread Id: 12
07:19:56.2854568 - Is Thread Pool Thread: True - Managed Thread Id: 15

In the code above we are setting the thread to wait 5 seconds, so after printing out to the console, the thread is kept alive for an additional 5 seconds before completing execution and returning to the Thread Pool. 在上面的代码中,我们将线程设置为等待5秒钟,因此,在将其输出到控制台后,该线程在执行完并返回到线程池之前,将保持活动状态另外5秒钟。

The timer carries on firing on each second regardless, it's not waiting on the thread it triggered to complete. 计时器每秒钟进行一次触发,而不管它是否等待触发的线程完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM