防止一个服务的多个实例 - 最佳方法? [英] Prevent multiple instance of a service - best approach?

查看:19
本文介绍了防止一个服务的多个实例 - 最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么您认为防止 C# Windows 服务的多个线程同时运行的最佳方法是什么(该服务使用 timerOnElapsed 事件)?

So what do you think is the best way to prevent multiple threads of a C# Windows service running simultaneously (the service is using a timer with the OnElapsed event) ?

使用 lock()mutex 吗?

我似乎无法理解 mutex 的概念,但使用 lock() 似乎对我的情况很有效.

I can't seem to grasp the concept of the mutex, but using lock() seems to work fine for my case.

我应该花时间学习如何使用 mutex 吗?

Should I spend the time learning how to use the mutex anyways?

推荐答案

使您的计时器成为一次性的,并在经过的事件处理程序中重新初始化它.例如,如果您使用 System.Timers.Timer,您可以像这样初始化它:

Make your timer a one-shot, and re-initialize it in the elapsed event handler. For example, if you're using System.Timers.Timer, you'd initialize it like this:

myTimer.Elapsed = timer1Elapsed;
myTimer.Interval = 1000; // every second
myTimer.AutoReset = false; // makes it fire only once
myTimer.Enabled = true;

还有你的 elapsed 事件处理程序:

And your elapsed event handler:

void timerElapsed(object source, ElapsedEventArgs e)
{
    // do whatever needs to be done
    myTimer.Start(); // re-enables the timer
}

这样做的缺点是计时器不会以一秒为间隔触发.相反,它会在最后一个滴答处理完成后一秒钟触发.

The drawback to this is that the timer doesn't fire on one second intervals. Rather, it fires one second after the last tick's processing finishes.

这篇关于防止一个服务的多个实例 - 最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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