C# System.Threading.Timer是否在两个不同的线程中运行?
下面是代码示例C# System.Threading.Timer是否在两个不同的线程中运行?,c#,.net,multithreading,timer,threadpool,C#,.net,Multithreading,Timer,Threadpool,下面是代码示例 using System.Threading; namespace TimerApp { class Program { static void Main(string[] args) { Console.WriteLine("***** Timer Application *****\n"); Console.WriteLine("In the thr
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,它是后台?True:时间是晚上10:38:00,参数是Main()的Hello(
…
按任意键继续
System.Threading.Timer
是否一次使用多个线程进行回调?它使用线程池,使用在每个时间间隔找到的第一个可用线程。计时器只是触发这些线程的触发
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();
}
输出
在上面的代码中,我们将线程设置为等待5秒,因此在打印到控制台后,线程在完成执行并返回到线程池之前将保持活动状态5秒
计时器每秒钟都会继续启动,不管它是否在等待它触发的线程完成。它利用线程池,使用它在每个时间间隔找到的第一个可用线程。计时器只是触发这些线程的触发
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();
}
输出
在上面的代码中,我们将线程设置为等待5秒,因此在打印到控制台后,线程在完成执行并返回到线程池之前将保持活动状态5秒
计时器每秒钟都会触发一次,而不是等待它触发的线程完成。回调是在线程池线程上进行的。线程池的隐含含义是,您永远不能假设它在池中的任何特定线程上运行。正如您所发现的那样。@Hans Passant那么每次新的回调调用都会使用线程池中不同的线程?您可以看到#4连续使用了两次。所以你知道事实并非如此。这主要是随机的,取决于程序和.NET框架中还发生了什么。使用Debug>Windows>Threads调试器窗口获取详细信息。回调是在线程池线程上进行的。线程池的隐含含义是,您永远不能假设它在池中的任何特定线程上运行。正如您所发现的那样。@Hans Passant那么每次新的回调调用都会使用线程池中不同的线程?您可以看到#4连续使用了两次。所以你知道事实并非如此。这主要是随机的,取决于程序和.NET框架中还发生了什么。使用Debug>Windows>Threads调试器窗口获取详细信息。