Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- using Topshelf;
- using Topshelf.Runtime;
- namespace MyConsoleApplication
- {
- public class MyService
- {
- public MyService(HostSettings settings)
- {
- }
- private SemaphoreSlim _semaphoreToRequestStop;
- private Thread _thread;
- public void Start()
- {
- _semaphoreToRequestStop = new SemaphoreSlim(0);
- _thread = new Thread(DoWork);
- _thread.Start();
- }
- public void Stop()
- {
- _semaphoreToRequestStop.Release();
- _thread.Join();
- }
- private void DoWork()
- {
- while (true)
- {
- Console.WriteLine("doing work..");
- if (_semaphoreToRequestStop.Wait(500))
- {
- Console.WriteLine("Stopped");
- break;
- }
- }
- }
- }
- public class Program
- {
- public static void Main()
- {
- HostFactory.Run(x =>
- {
- x.StartAutomatically(); // Start the service automatically
- x.EnableServiceRecovery(rc =>
- {
- rc.RestartService(1); // restart the service after 1 minute
- });
- x.Service<MyService>(s =>
- {
- s.ConstructUsing(hostSettings => new MyService(hostSettings));
- s.WhenStarted(tc => tc.Start());
- s.WhenStopped(tc => tc.Stop());
- });
- x.RunAsLocalSystem();
- x.SetDescription("MyDescription");
- x.SetDisplayName("MyDisplayName");
- x.SetServiceName("MyServiceName");
- });
- }
- }
- }
- Tutorial on http://stackoverflow.com/questions/18206738/installing-a-topshelf-application-as-a-windows-service
Advertisement
Add Comment
Please, Sign In to add comment