C#定时器是否启动新线程? [英] Does C# timers start new thread?

查看:345
本文介绍了C#定时器是否启动新线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我想知道C#定时器占用新线程还是在主线程上工作?

我有一个控制台应用程序,我有一些运行或主线程,需要4-5个小时。在4-5小时内,我每隔5分钟就会运行一些代码。所以我可以使用计时器,以便它启动新线程并在主线程仍在运行时执行。或者我必须为计时器制作线程?

解决方案

来自msdn 文档 [ ^ ] -

System.Threading.Timer是一个简单,轻量级的计时器,使用回调方法并由线程池线程提供服务。建议不要与Windows窗体一起使用,因为它的回调不会发生在用户界面线程上。对于Windows窗体,System.Windows.Forms.Timer是更好的选择。对于基于服务器的计时器功能,您可以考虑使用System.Timers.Timer,它会引发事件并具有其他功能。



此外,请查看这个答案 [ ^ ]。


说实话,我根本不会使用计时器。

相反,我会在BackgroundWorker线程上设置代码,并调用Thread.Sleep在运行之间暂停:

 BackgroundWorker工作=  new  BackgroundWorker(); 
work.DoWork + = new DoWorkEventHandler(work_DoWork);
work.RunWorkerAsync();
...

void work_DoWork( object sender,DoWorkEventArgs e)
{
while true
{
RunYourCodeHere();
System.Threading.Thread.Sleep( 5 * 60 * 1000 ); // 等待五分钟
}
}


Hello guys,
I want to know that does C# timers take up new thread or they work on the main thread?
I am having a console app where I have something running or main thread and it takes 4-5 hours. In those 4-5 hours, at every 5 mins I want to run some code. So can I use timer so that it starts new thread and execute while main thread is still running. Or i will have to make thread for timer?

解决方案

From msdn documentation [^]-
"System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features."

Also, check out this answer[^].


To be honest, I wouldn't use a timer at all.
Instead, I would set up the code on a BackgroundWorker thread instead, and call Thread.Sleep to pause between runs:

BackgroundWorker work = new BackgroundWorker();
    work.DoWork += new DoWorkEventHandler(work_DoWork);
    work.RunWorkerAsync();
    ...

void work_DoWork(object sender, DoWorkEventArgs e)
    {
    while (true)
        {
        RunYourCodeHere();
        System.Threading.Thread.Sleep(5 * 60 * 1000);  // Wait five minutes
        }
    }


这篇关于C#定时器是否启动新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆