首页
视频
资源
登录
原
.net Thread.Sleep长时间睡眠的问题
7219
人阅读
2021/2/2 11:08
总访问:
2534603
评论:
1
收藏:
0
手机
分类:
.net后台框架
![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net Thread.Sleep长时间睡眠的问题 [TOC] tn>在工作中,不知道大家有没有发现,`Thread.Sleep`如果设置的时间过长,会导致它就像人睡着了一样到点了都不醒过来。但如果你在它睡眠的时候去按一下回车键多按几下,它就醒了。这就会让我觉得它要长时间睡眠后不能保证我的服务得以正常的运行。网友说:它仅保证将线程至少暂停这么多秒,因为它基于针对不同Windows版本的时间片编号。具体问题可以看看这个:https://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/ >### 解决问题 tn>那么如何解决呢?我们可以通过调度的方式来解决。在最高级别上,您可以使用`Quartz.NET`库,但是如果您不需要任何大的逻辑来安排执行时间,那么这会有些负担。 可以使用的一件事是 `System.Threading.AutoResetEvent` 与`System.Timers.Timer`类结合。以下是在无限循环中使用`Timer`和`AutoResetEvent`的示例,该循环是错误使用`Thread.Sleep`的最常见地方。 ```csharp /// <summary> /// 我们将它设置10秒调度一次 /// </summary> static readonly System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds) { AutoReset = true }; /// <summary> /// 我们将第一次不让它过让它为false /// </summary> static readonly AutoResetEvent autoResetEvent = new AutoResetEvent(false); static void Main(string[] args) { timer.Elapsed += Timer_Elapsed; timer.Start(); ThreadPool.QueueUserWorkItem((state) => { while (true) { Console.WriteLine(DateTime.Now); autoResetEvent.WaitOne(); } }); Console.ReadLine(); } /// <summary> /// 调度的事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void Timer_Elapsed(object sender, ElapsedEventArgs e) { autoResetEvent.Set(); } ``` tn>实际上,我们不必依赖`Thread.Sleep`切片,而是可以使用`Timer`设置事件并安排`Thread`执行。由于它是`AutoResetEvent`而不是`ManualResetEvent`,因此一旦线程执行,我们将自动重置事件。 ![](https://img.tnblog.net/arcimg/hb/4776197e4e0e4e4594dd842364a014f1.png)
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
👈{{preArticle.title}}
👉{{nextArticle.title}}
评价
{{titleitem}}
{{titleitem}}
{{item.content}}
{{titleitem}}
{{titleitem}}
{{item.content}}
尘叶心繁
这一世以无限游戏为使命!
博主信息
排名
6
文章
6
粉丝
16
评论
8
文章类别
.net后台框架
166篇
linux
17篇
linux中cve
1篇
windows中cve
0篇
资源分享
10篇
Win32
3篇
前端
28篇
传说中的c
4篇
Xamarin
9篇
docker
15篇
容器编排
101篇
grpc
4篇
Go
15篇
yaml模板
1篇
理论
2篇
更多
Sqlserver
4篇
云产品
39篇
git
3篇
Unity
1篇
考证
2篇
RabbitMq
23篇
Harbor
1篇
Ansible
8篇
Jenkins
17篇
Vue
1篇
Ids4
18篇
istio
1篇
架构
2篇
网络
7篇
windbg
4篇
AI
18篇
threejs
2篇
人物
1篇
嵌入式
2篇
python
13篇
HuggingFace
8篇
pytorch
9篇
opencv
6篇
最新文章
最新评价
{{item.articleTitle}}
{{item.blogName}}
:
{{item.content}}
关于我们
ICP备案 :
渝ICP备18016597号-1
网站信息:
2018-2024
TNBLOG.NET
技术交流:
群号656732739
联系我们:
contact@tnblog.net
欢迎加群
欢迎加群交流技术