注意:假如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
{
class Program : System.ServiceProcess.ServiceBase
{
/// <summary>
/// name of the service
/// </summary>
internal const string Name = "Mediaroom test Service";
/// <summary>
/// stop migration
/// </summary>
private ManualResetEvent stopMigration = new ManualResetEvent(false);
private ManualResetEvent stopMigration1 = new ManualResetEvent(false);
/// <summary>
/// thread for migration
/// </summary>
private Thread 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>
protected override void OnStart(string[] args)
{
StartMigrationThread();
// Logger.LogInformation("{0} is started", this.ServiceName);
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
StopService();
}
protected void StopService()
{
//stopMigration.Set();
//stopMigration1.WaitOne();
//Logger.LogInformation("{0} will be stopped soon after the processing jobs are completed.", this.ServiceName);
}
protected void StartMigrationThread()
{
migrationThread = new Thread(DoMigrationJobs);
migrationThread.IsBackground = true;
migrationThread.Start();
//Logger.LogInformation("Migration thread is started");
}
private void DoMigrationJobs()
{
//while(!stopMigration.WaitOne(0))
while(true)
{
Thread.Sleep(1000);
}
// Thread.Sleep(3 * 60000);
//stopMigration1.Set();
}
static void 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[] { new Program() };
System.ServiceProcess.ServiceBase.Run(servicesToRun);
}
}
}