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

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

问题描述

那么,你认为是为了防止同时运行一个C#Windows服务的多线程的最佳方法(该服务使用的是定时 OnElapsed 事件)?

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) ?

使用锁()互斥

我似乎无法把握互斥的概念 ,但使用锁()似乎我的情况很好地工作。

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

我应该花时间学习如何使用互斥反正?

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;

和你经过的事件处理程序:

And your elapsed event handler:

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



这个的缺点是计时器没有按T火每隔一秒。相反,它激发了最后一跳的处理完成后一秒。

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天全站免登陆