调用ServiceBase.OnStart和OnStop …同样的实例?
所以我有一个用c#编写的Windows服务。 服务类派生自ServiceBase
,启动和停止服务分别调用实例方法OnStart
和OnStop
。 这是class上的SSCE:
partial class CometService : ServiceBase { private Server server; private ManualResetEvent mre; public CometService() { InitializeComponent(); } protected override void OnStart(string[] args) { //starting the server takes a while, but we need to complete quickly //here so let's spin off a thread so we can return pronto. new Thread(() => { try { server = new Server(); } finally { mre.Set() } }) { IsBackground = false }.Start(); } protected override void OnStop() { //ensure start logic is completed before continuing mre.WaitOne(); server.Stop(); } }
可以看出,有很多逻辑要求当我们调用OnStop
,我们处理的ServiceBase
实例与调用OnStart
时相同。
我能确定是这种情况吗?
如果您查看Program.cs
类,您将看到如下代码:
private static void Main() { ServiceBase.Run(new ServiceBase[] { new CometService() }); }
也就是说,实例是由您自己项目中的代码创建的。 这是所有Service Manager调用的一个实例(包括OnStart
和OnStop
)。
我想是同一个例子。 您可以快速测试在类中添加静态字段,以跟踪对OnStart中使用的对象的引用,并将其与OnStop的实例进行比较。
private static CometService instance = null; protected override void OnStart(...) { instance = this; ... } protected override void OnStop() { object.ReferenceEquals(this, instance); ... }