Timer 线程池和线程。计时器?
我有一个关于线程中计时器的问题 我的代码:Timer 线程池和线程。计时器?,timer,threadpool,Timer,Threadpool,我有一个关于线程中计时器的问题 我的代码: public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Testing testing = new Testing(); Thread th
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Testing testing = new Testing();
Thread thread = new Thread(new ThreadStart(delegate
{
testing.Start();
}));
thread.IsBackground = true;
thread.Start();
}
}
public class Testing
{
System.Threading.Timer timer = null;
public void Start()
{
if (timer == null)
timer = new System.Threading.Timer(timerTick, null, 500, 500);
List<ManualResetEvent> amanual = new List<ManualResetEvent>();
for (int index = 0; index < 10; index++)
{
ManualResetEvent manual = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object context)
{
this.RunningThreadPool(context);
manual.Set();
}
));
amanual.Add(manual);
}
WaitHandle.WaitAll(amanual.ToArray());
Console.WriteLine("Task complete");
}
void timerTick(object sender)
{
Console.WriteLine("Timer running");
}
public void RunningThreadPool(object context)
{
Console.WriteLine("Thread in Threadpool is running...");
}
}
}
这就是结果
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
线程池中的线程正在运行。。。
任务完成
计时器运行
计时器运行
计时器运行
计时器运行
我有一个问题,在线程池执行之前,计时器如何运行。除了在线程池上设置计时器。因为我需要线程池上的计时器检查线程 我想说,500毫秒的时间足够完成您的工作队列,甚至在计时器触发一次之前。10 Console.WriteLine调用不会带来太多工作 假设您运行的工作负载稍重:
计时器在线程池中运行其回调,因此它在其他工作排队后排队。。。i、 它是队列中的最后一个。由于您排队的项目比线程池中的线程多,并且线程池仅在长时间加载的情况下启动新线程,因此线程池无法及时执行计时器的回调。但我没有将计时器排队到线程池。有什么解决办法吗,@spender?@HùngLèXu–n没有,但计时器将其回调在线程池中排队。阅读“备注”下的第二个项目符号,这就是为什么在线程池中运行繁重的工作负载并用工作压倒它是有问题的。许多.Net API依赖于线程池剩余的流体,这可能会在应用程序中引入意外的延迟。考虑在自己的线程中执行这项工作。