gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:04:32 28 4
gpt4 key购买 nike

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

    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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com