Window service OnStop会立即关闭整个进程

来源:互联网 发布:java接收微信事件推送 编辑:程序博客网 时间:2024/06/06 23:46


注意:假如workerthread是一个死循环,我们的windows service能立即关掉吗?答案是是的。一旦主线程关闭,它不关心worker thread是否还在工作,立即关闭整个进程。


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.ServiceProcess;

using System.Threading;

namespace WindowsServiceTest

{

classProgram : System.ServiceProcess.ServiceBase

{

///<summary>

/// name of the service

///</summary>

internalconststring Name = "Mediaroom test Service";

///<summary>

/// stop migration

///</summary>

privateManualResetEvent stopMigration = newManualResetEvent(false);

privateManualResetEvent stopMigration1 = newManualResetEvent(false);

///<summary>

/// thread for migration

///</summary>

privateThread migrationThread;

public Program()

{

this.ServiceName = Name;

}

///<summary>

/// Set things in motion so your service can do its work.

///</summary>

///<param name="args">arguments to start</param>

protectedoverridevoid OnStart(string[] args)

{

StartMigrationThread();

// Logger.LogInformation("{0} is started", this.ServiceName);

}

///<summary>

/// Stop this service.

///</summary>

protectedoverridevoid OnStop()

{

StopService();

}

protectedvoid StopService()

{

//stopMigration.Set();

//stopMigration1.WaitOne();

//Logger.LogInformation("{0} will be stopped soon after the processing jobs are completed.", this.ServiceName);

}

protectedvoid StartMigrationThread()

{

migrationThread =newThread(DoMigrationJobs);

migrationThread.IsBackground =true;

migrationThread.Start();

//Logger.LogInformation("Migration thread is started");

}

privatevoid DoMigrationJobs()

{

//while(!stopMigration.WaitOne(0))

while(true)

{

Thread.Sleep(1000);

}

           // Thread.Sleep(3 * 60000);

//stopMigration1.Set();

}

staticvoid Main(string[] args)

{

System.ServiceProcess.ServiceBase[] servicesToRun;

// More than one user Service may run within the same process. To add

// another service to this process, change the following line to

// create a second service object. For example,

//

// servicesToRun = new System.ServiceProcess.ServiceBase[] {new SchedulerService(), new MySecondUserService()};

servicesToRun =new System.ServiceProcess.ServiceBase[] { newProgram() };

System.ServiceProcess.ServiceBase.Run(servicesToRun);

}

}

}

0 0
原创粉丝点击