【发布时间】:2016-12-17 03:52:34
【问题描述】:
下面的代码示例
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());
}
}
}
产生以下输出
***** 定时器应用程序 *****
在线程 #1
点击键终止...
从线程 #4 来看,它是背景?是的:时间是晚上 10:37:54,参数是来自 Main() 的 Hello
从线程 #4 来看,它是背景?是的:时间是晚上 10:37:55,参数是来自 Main() 的 Hello
从线程 #5,它是背景?是的:时间是晚上 10:37:56,参数是来自 Main() 的 Hello
从线程 #4,它是背景?是的:时间是晚上 10:37:57,参数是来自 Main() 的 Hello
从线程 #5 来看,它是背景?是的:时间是晚上 10:37:58,参数是来自 Main() 的 Hello
从线程 #4 来看,它是背景?是的:时间是晚上 10:37:59,参数是来自 Main() 的 Hello
从线程 #5 来看,它是背景?是的:时间是晚上 10:38:00,参数是来自 Main() 的 Hello
...
按任意键继续 。 . .
System.Threading.Timer 是否一次使用多个线程进行回调?
【问题讨论】:
-
回调是在线程池线程上进行的。关于线程池的隐含意义是,您永远不能假设它运行在池中的任何特定线程上。如你所见。
-
@Hans Passant 所以每个新的回调调用都使用线程池中的不同线程?
-
您可以看到#4 连续使用了两次。所以你知道事实并非如此。它主要是随机的,取决于您的程序和 .NET Framework 中还发生了什么。使用 Debug > Windows > Threads 调试器窗口来获得洞察力。
标签: c# .net multithreading timer threadpool