Guest User

TopShelf Windows-Service example

a guest
Mar 29th, 2016
1,367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using Topshelf;
  4. using Topshelf.Runtime;
  5.  
  6. namespace MyConsoleApplication
  7. {
  8.     public class MyService
  9.     {
  10.         public MyService(HostSettings settings)
  11.         {
  12.         }
  13.  
  14.         private SemaphoreSlim _semaphoreToRequestStop;
  15.         private Thread _thread;
  16.  
  17.         public void Start()
  18.         {
  19.             _semaphoreToRequestStop = new SemaphoreSlim(0);
  20.             _thread = new Thread(DoWork);
  21.             _thread.Start();
  22.         }
  23.  
  24.         public void Stop()
  25.         {
  26.             _semaphoreToRequestStop.Release();
  27.             _thread.Join();
  28.         }
  29.  
  30.         private void DoWork()
  31.         {
  32.             while (true)
  33.             {
  34.                 Console.WriteLine("doing work..");
  35.                 if (_semaphoreToRequestStop.Wait(500))
  36.                 {
  37.                     Console.WriteLine("Stopped");
  38.                     break;
  39.                 }
  40.             }
  41.         }
  42.     }
  43.  
  44.     public class Program
  45.     {
  46.         public static void Main()
  47.         {
  48.  
  49.             HostFactory.Run(x =>                                
  50.             {
  51.                 x.StartAutomatically(); // Start the service automatically
  52.  
  53.                 x.EnableServiceRecovery(rc =>
  54.                 {
  55.                     rc.RestartService(1); // restart the service after 1 minute
  56.                 });
  57.  
  58.  
  59.                 x.Service<MyService>(s =>
  60.                 {
  61.                     s.ConstructUsing(hostSettings => new MyService(hostSettings));
  62.                     s.WhenStarted(tc => tc.Start());            
  63.                     s.WhenStopped(tc => tc.Stop());              
  64.                 });
  65.                 x.RunAsLocalSystem();                            
  66.  
  67.                 x.SetDescription("MyDescription");        
  68.                 x.SetDisplayName("MyDisplayName");                      
  69.                 x.SetServiceName("MyServiceName");    
  70.                                    
  71.             });                                                
  72.         }
  73.     }
  74. }
  75.  
  76. Tutorial on http://stackoverflow.com/questions/18206738/installing-a-topshelf-application-as-a-windows-service
Advertisement
Add Comment
Please, Sign In to add comment