System.Timers.Timer/Threading.Timer vs Thread with WhileLoop + Thread.Sleep For Periodic Tasks [英] System.Timers.Timer/Threading.Timer vs Thread with WhileLoop + Thread.Sleep For Periodic Tasks

查看:32
本文介绍了System.Timers.Timer/Threading.Timer vs Thread with WhileLoop + Thread.Sleep For Periodic Tasks的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我必须定期向兄弟"应用程序发送心跳.

In my application I have to send periodic heartbeats to a "brother" application.

使用 System.Timers.Timer/Threading.Timer 还是使用带有 while 循环和 Thread.Sleep 的线程更好?

Is this better accomplished with System.Timers.Timer/Threading.Timer or Using a Thread with a while loop and a Thread.Sleep?

心跳间隔为1秒.

while(!exit)
{
   //do work
   Thread.Sleep(1000);
}

myTimer.Start( () => { 
                       //do work 
                      }, 1000); //pseudo code (not actual syntax)...

推荐答案

System.Threading.Timer 有我的投票权.

System.Timers.Timer 旨在用于基于服务器(您的代码在主机上作为服务器/服务运行,而不是由用户运行)计时器功能.

System.Timers.Timer is meant for use in server-based (your code is running as a server/service on a host machine rather than being run by a user) timer functionality.

考虑到 .NET 中存在更强大的计时器机制,具有 While 循环和 Thread.Sleep 命令的线程确实是一个坏主意.

A Thread with a While loop and Thread.Sleep command is truly a bad idea given the existance of more robust Timer mecahnisms in .NET.

这篇关于System.Timers.Timer/Threading.Timer vs Thread with WhileLoop + Thread.Sleep For Periodic Tasks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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