c# - System.Threading.Timer 和在 C# 中创建自己的后台滴答线程之间有什么区别

标签 c# .net multithreading timer

我有一个结构如下的背景刻度函数:

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

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

但是,还有一个 System.Threading.Timer 类可以为我执行此操作。使用 System.Threading 中存在的内置 Timer 类而不是使用 Tick 函数创建我自己的后台线程有什么区别?

最佳答案

与在无限 do while 循环中休眠指定时间的您自己的专用线程相比,Timer 类的重量非常轻且效率更高。

请阅读 Thread.Sleep is a sign of a poorly designed program了解 Thread.Sleep 的实际工作原理以及它如何浪费完整的线程和资源

另一方面,System.Threading.Timer 将使用 ThreadPool 线程来执行计时器。如我的 MSDN 所述,使用 Timer 类的其他好处

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.

在基于线程的方法中你不会有这些好处

关于c# - System.Threading.Timer 和在 C# 中创建自己的后台滴答线程之间有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8928851/

相关文章:

c# - 将 Azure 仪表板集成到自定义 Web 应用程序中

根据 CPU 和 RAM 使用情况调整线程池的 Java Executor

c++ - C++11 线程是否为分离线程提供了一种在主线程退出后继续运行的方法?

c# - 全景图和图像阵列

c# - 如何将自定义配置提供程序添加到azure函数

.net - windbg 在 dll 函数调用级别调试 outlook 插件

c# - 如何强行释放MemoryStream占用的内存?

c# - 什么时候选择套接字编程而不是 WCF?

c++ - 当boost线程被回收时,在其中创建的临时变量会从内存中删除吗?

c# - 01/01/1900 的日期时间问题