什么是C#System.Threading.Timer和创建自己的背景打勾线程之间的区别 [英] What are the differences between System.Threading.Timer and creating your own background tick thread in C#

查看:414
本文介绍了什么是C#System.Threading.Timer和创建自己的背景打勾线程之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是结构化的背景打勾功能如下:

I have a background tick function that is structured as follows:

    System.Threading.Thread myTimerThread = new Thread(this.Tick);

    private void Tick(){
       do{
          //do stuff
          System.Threading.Sleep(1000L);
       }while(true)    
    }

然而,也有,这是否对我来说是System.Threading.Timer类。什么是使用内置的Timer类present中的System.Threading而不是创造我自己的后台线程带勾的功能有何区别?

However, there is also a System.Threading.Timer class that does this for me. What are the differences in using the built in Timer class present in System.Threading rather than creating my own background thread with a Tick function?

推荐答案

Timer类是非常轻的重量和比你自己的专用线程是睡在指定的时间内无限更有效的做while循环。

The Timer class would be very light weight and more efficient as compared to your own dedicated thread which is sleeping for a specified time inside infinite do while loop.

不要读<一href="http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx"相对=nofollow> Thread.sleep代码是一个设计不当的计划为找出了Thread.Sleep实际上是如何工作的,以及它如何浪费了完整的线程和资源的标志

Do read Thread.Sleep is a sign of a poorly designed program for finding out how Thread.Sleep actually works and how it wastes a complete thread and resources

在另一方面System.Threading.Timer将使用线程池线程来执行定时器。使用Timer类的描述我的MSDN的另一个好处

On the other hand System.Threading.Timer will use ThreadPool thread to execute the timer. Other benefit of using Timer class as described my MSDN

当你创建一个定时器,可以指定时间之前,要等待量   第一执行的方法(由于时间),和时间之间等待的量   后续的执行(周期)。您可以使用更改方法改变这些值,或关闭计时器。

When you create a timer, you can specify an amount of time to wait before the first execution of the method (due time), and an amount of time to wait between subsequent executions (period). You can change these values, or disable the timer, using the Change method.

您不会有基于线程的方法,这些好处

You won't have these benefits in thread based approach

这篇关于什么是C#System.Threading.Timer和创建自己的背景打勾线程之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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