螺纹VS定时器在C# [英] Thread vs Timer in C#

查看:126
本文介绍了螺纹VS定时器在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查的数据来的两个实现:

I have two implementations of checking for data coming:

使用 System.Timers.Timer

public void startTimer()
{
    try
    {
         System.Timers.Timer timer = new System.Timers.Timer(1);
         timer.AutoReset = true;
         timer.Elapsed += new ElapsedEventHandler(commStart);
         timer.Enabled = true;
         timer.Start();
    }
    catch(Exception ex){}
}

private void commStart(){object sender, EventArgs eArgs}

使用

public void startThread()
{
   Thread threadGeneralComm = new Thread(new ThreadStart(commStart));

   threadGeneralComm.Start()
}

private void commStart()
{
   while(true)
   {
       // checking data
       Thread.Sleep(1);
   }
}



所以你可以看到,两者的实现方式,它会检查数据并等待1毫秒。人们都在抱怨,我认为使用定时器比使用线程差。使用线程是快10倍。我希望能有一些意见/建议这一点。

So you can see, both of the implementation ways, it will check for data and wait for 1 millisecond. People are complaining to me that using Timer is worse than using Thread. Using Thread is 10 times faster. I hope to have some opinions/advices for this.

您能帮我澄清这件事?

先谢谢了。

推荐答案

这两个选项是穷人。他们是轮询方法,因此将使用CPU进行时,有没有数据没有理由。

Both options are poor. They are polling methods and so will use CPU for no reason when there is no data.

如果您不能使用事件驱动的方法,那么你应该寻找一个解决方案基于一个阻塞队列。

If you can't use an event driven approach then you should look for a solution based on a blocking queue.

这篇关于螺纹VS定时器在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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