更好的方式来不断地在C#中定期运行功能 [英] Better way to constantly run function periodically in C#
问题描述
我有一个不断检查新增加的一个在线数据库C#程序。我有这样的代码有它检查每10秒
I have a C# program that is constantly checking for new additions to an online DB. I have this code to have it check every 10 seconds
static void Main(string[] args)
{
boolean run = true;
while (run)
{
DBConnect Db = new DBConnect();
// do amazing awesome mind blowing cool stuff
Db.closeConnection();
// wait for 10 seconds
int wait = 10 * 1000;
System.Threading.Thread.Sleep(wait);
}
}
我的错误报告的帖子到数据库,如果出现重大错误的程序关闭。我的函数内的特定错误之外,就是这种方法安全有效的?
i have error reporting that posts to the DB and if a major error occurs the program shuts down. Outside of the specific errors within my function, is this method secure and efficient?
推荐答案
您应该重写你的程序作为Windows服务,要记录你的程序运行方式,您不需要依赖用户。
You should rewrite your program as a windows service, that way you do not need to rely on a user to be logged for your program to run.
如果你的服务的路线走,我会换出。无限循环的一个计时器
If you do go with the service route, I would swap out the infinite loop for a timer.
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
int wait = 10 * 1000;
timer = new Timer(wait);
timer.Elapsed += timer_Elapsed;
// We don't want the timer to start ticking again till we tell it to.
timer.AutoReset = false;
}
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
timer.Start();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
try
{
DBConnect Db = new DBConnect())
// do amazing awesome mind blowing cool stuff
}
finally
{
Db.closeConnection(); //We put this in a finally block so it will still happen, even if an exception is thrown.
}
timer.Start();
}
catch(SomeNonCriticalException ex)
{
MyExecptionLogger.Log(ex, Level.Waring); //Log the exception so you know what went wrong
timer.Start(); //Start the timer for the next loop
}
catch(Exception ex)
{
MyExecptionLogger.Log(ex, Level.Critical); //Log the exception so you know what went wrong
this.Stop(); //Stop the service
}
}
protected override void OnStop()
{
timer.Stop();
}
}
这篇关于更好的方式来不断地在C#中定期运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!