Loading... Please wait...
  
Contact Code Collections | About Code Collections
  
 
             | 
X Sections
Code News RSS
Links
Developer Sites
License Types
Service Base PDF Print E-mail
Written by Phillip Brown   
Saturday, 23 September 2006
language: csharp
  1. public abstract class Base : ServiceBase {
  2. protected Thread m_ServiceThread;
  3. protected ManualResetEvent m_ShutdownEvent;
  4. protected TimeSpan m_ServiceDelay;
  5.  
  6. public Base() {
  7. // Set our service loop time to a default of 1 second
  8. // this can be changed by the property below
  9. // this may later be defaulted to a larger value
  10. m_ServiceDelay = new TimeSpan(0, 0, 1);
  11. }
  12.  
  13. public TimeSpan Delay {
  14. set { m_ServiceDelay = value;}
  15. }
  16.  
  17. protected override void OnStart(string[] args) // We are overriding the OnStart method in our ServiceBase base.
  18. {
  19. // create our threadstart object to wrap our delegate method
  20. ThreadStart _ThreadStart = new ThreadStart(this.ServiceMain);
  21.  
  22. // create the manual reset event and
  23. // set it to an initial state of unsignaled
  24. m_ShutdownEvent = new ManualResetEvent(false);
  25.  
  26. // create the worker thread
  27. m_ServiceThread = new Thread(_ThreadStart);
  28.  
  29. // go ahead and start the worker thread
  30. m_ServiceThread.Start();
  31.  
  32. // call the base class so it has a chance
  33. // to perform any work it needs to
  34. base.OnStart(args);
  35. }
  36.  
  37. protected override void OnStop() {
  38. // signal the event to shutdown
  39. m_ShutdownEvent.Set();
  40.  
  41. // wait for the thread to stop
  42. m_ServiceThread.Join((int)m_ServiceDelay.TotalSeconds);
  43.  
  44. // call the base class
  45. base.OnStop();
  46. }
  47.  
  48. protected virtual void ServiceMain() {
  49. bool bSignaled = false;
  50.  
  51. Initialize();
  52.  
  53. while (true) {
  54. // wait for the event to be signaled
  55. // or for the configured delay
  56. bSignaled = m_ShutdownEvent.WaitOne(m_ServiceDelay, true);
  57.  
  58. // if we were signaled to shutdown, exit the loop
  59. if (bSignaled == true)
  60. break;
  61.  
  62. // let's do some work
  63. ServiceThread();
  64. }
  65.  
  66. Dispose();
  67. }
  68.  
  69. protected virtual void ServiceThread() {
  70. return;
  71. }
  72.  
  73. protected virtual void Initialize() {
  74. return;
  75. }
  76.  
  77. protected virtual new void Dispose() {
  78. return;
  79. }
  80. }
  81.  
Comments
Add NewSearchRSS
Only registered users can write comments!
Last Updated ( Monday, 06 November 2006 )
 
< Prev
Page was generated in 0.036357 seconds