WindowsService

using System;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;
using Vod.Domain;
using Vod.Service.DomainService;

namespace Vod.FileMonitorWindowsService
{
    
public enum ServiceCustomCommands { StopWorker = 128, RestartWorker, CheckWorker };
    [StructLayout(LayoutKind.Sequential)]
    
public struct SERVICE_STATUS
    {
        
public int serviceType;
        
public int currentState;
        
public int controlsAccepted;
        
public int win32ExitCode;
        
public int serviceSpecificExitCode;
        
public int checkPoint;
        
public int waitHint;
    }

    
public enum State
    {
        SERVICE_STOPPED 
= 0x00000001,
        SERVICE_START_PENDING 
= 0x00000002,
        SERVICE_STOP_PENDING 
= 0x00000003,
        SERVICE_RUNNING 
= 0x00000004,
        SERVICE_CONTINUE_PENDING 
= 0x00000005,
        SERVICE_PAUSE_PENDING 
= 0x00000006,
        SERVICE_PAUSED 
= 0x00000007,
    }

    partial 
class FileMonitorService : ServiceBase
    {
        
public static ScanService scanService = new ScanService();
        
private static ManualResetEvent pause = new ManualResetEvent(false);

        [DllImport(
"ADVAPI32.DLL", EntryPoint = "SetServiceStatus")]
        
public static extern bool SetServiceStatus(
                        IntPtr hServiceStatus,
                        SERVICE_STATUS lpServiceStatus
                        );
        
private SERVICE_STATUS myServiceStatus;

        
private Thread workerThread = null;

        
public FileMonitorService()
        {
            InitializeComponent();
        }

        
protected override void OnStart(string[] args)
        {
            Common.WriteLog(
@"C:\Vod.FileMonitorWindowsService.txt"" FileMonitorWindowsService:        OnStart " + DateTime.Now + "\n");
            IntPtr handle 
= ServiceHandle;
            
            myServiceStatus.currentState 
= (int)State.SERVICE_START_PENDING;
            SetServiceStatus(handle, myServiceStatus);

            
// Start a separate thread that does the actual work.

            
if ((workerThread == null||
                ((workerThread.ThreadState 
&
                 (ThreadState.Unstarted 
| ThreadState.Stopped)) != 0))
            {
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.OnStart", DateTime.Now.ToLongTimeString() +
                    
" - Starting the service worker thread.");
#endif

                workerThread 
= new Thread(new ThreadStart(ServiceWorkerMethod));
                workerThread.Start();
            }
            
if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.OnStart", DateTime.Now.ToLongTimeString() +
                    
" - Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
            myServiceStatus.currentState 
= (int)State.SERVICE_RUNNING;
            SetServiceStatus(handle, myServiceStatus);

        }
        
protected override void OnStop()
        {
            
// New in .NET Framework version 2.0.
            RequestAdditionalTime(4000);
            
// Signal the worker thread to exit.
            if ((workerThread != null&& (workerThread.IsAlive))
            {
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.OnStop", DateTime.Now.ToLongTimeString() +
                    
" - Stopping the service worker thread.");
#endif
                pause.Reset();
                Thread.Sleep(
5000);
                workerThread.Abort();
            }
            
if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.OnStop", DateTime.Now.ToLongTimeString() +
                    
" - OnStop Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
            
// Indicate a successful exit.
            ExitCode = 0;
        }
        
// Pause the service.
        protected override void OnPause()
        {
            
// Pause the worker thread.
            if ((workerThread != null&&
                (workerThread.IsAlive) 
&&
                ((workerThread.ThreadState 
&
                 (ThreadState.Suspended 
| ThreadState.SuspendRequested)) == 0))
            {
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.OnPause", DateTime.Now.ToLongTimeString() +
                    
" - Pausing the service worker thread.");
#endif

                pause.Reset();
                Thread.Sleep(
5000);
            }

            
if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.OnPause", DateTime.Now.ToLongTimeString() +
                    
" OnPause - Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
        }

        
// Continue a paused service.
        protected override void OnContinue()
        {

            
// Signal the worker thread to continue.
            if ((workerThread != null&&
                ((workerThread.ThreadState 
&
                 (ThreadState.Suspended 
| ThreadState.SuspendRequested)) != 0))
            {
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.OnContinue", DateTime.Now.ToLongTimeString() +
                    
" - Resuming the service worker thread.");

#endif
                pause.Set();
            }
            
if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.OnContinue", DateTime.Now.ToLongTimeString() +
                    
" OnContinue - Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
        }

        
// Handle a custom command.
        protected override void OnCustomCommand(int command)
        {
#if LOGEVENTS
            EventLog.WriteEntry(
"FileMonitorWindowsService.OnCustomCommand", DateTime.Now.ToLongTimeString() +
                
" - Custom command received: " +
                command.ToString());
#endif

            
// If the custom command is recognized,
            
// signal the worker thread appropriately.

            
switch (command)
            {
                
case (int)ServiceCustomCommands.StopWorker:
                    
// Signal the worker thread to terminate.
                    
// For this custom command, the main service
                    
// continues to run without a worker thread.
                    OnStop();
                    
break;

                
case (int)ServiceCustomCommands.RestartWorker:

                    
// Restart the worker thread if necessary.
                    OnStart(null);
                    
break;

                
case (int)ServiceCustomCommands.CheckWorker:
#if LOGEVENTS
                    
// Log the current worker thread state.
                    EventLog.WriteEntry("FileMonitorWindowsService.OnCustomCommand", DateTime.Now.ToLongTimeString() +
                        
" OnCustomCommand - Worker thread state = " +
                        workerThread.ThreadState.ToString());
#endif

                    
break;

                
default:
#if LOGEVENTS
                    EventLog.WriteEntry(
"FileMonitorWindowsService.OnCustomCommand"
                        DateTime.Now.ToLongTimeString());
#endif
                    
break;
            }
        }

        
// Define a simple method that runs as the worker thread for 
        
// the service.  
        public void ServiceWorkerMethod()
        {
#if LOGEVENTS
            EventLog.WriteEntry(
"FileMonitorWindowsService.WorkerThread", DateTime.Now.ToLongTimeString() +
                
" - Starting the service worker thread.");
#endif

            
try
            {
                
do
                {
                    
// Simulate scanSetting.Interval seconds of work.
                    ScanSetting scanSetting = Common.GetCurrentScanSetting();
                    
if (scanSetting != null)
                    {
                        
if (scanSetting.Interval > 0)
                            scanSetting.NextScanDate 
= DateTime.Now.AddMinutes(scanSetting.Interval);
                        
else 
                            scanSetting.NextScanDate 
= DateTime.Now.AddMinutes(10);
                        scanService.UpdateScanSetting(scanSetting);
                        
if(scanSetting.IsRunning==1)
                        {
                            Common.AddUnAddedHostResource();
                            
if (scanSetting.Interval > 0)
                                Thread.Sleep(
1000 * 60 * scanSetting.Interval);
                            
else
                                Thread.Sleep(
1000 * 60 * 10);//默认10分钟
                        }else
                        {
                            Thread.Sleep(
1000 * 60 * 1);//默认2分钟
                        }
                           
                    }
else
                    {
                        Thread.Sleep(
1000 * 60 * 1);//默认10分钟
                    }
                    Common.WriteLog(
@"C:\Vod.FileMonitorWindowsService.txt"" FileMonitorWindowsService:        ServiceWorkerMethod " + DateTime.Now + "\n");
                    
// Block if the service is paused or is shutting down.
                    
//pause.WaitOne();
#if LOGEVENTS
                    EventLog.WriteEntry(
"FileMonitorWindowsService.WorkerThread", DateTime.Now.ToLongTimeString() +
                        
" - heartbeat cycle.");
#endif
                }
                
while (true);
            }
            
catch (ThreadAbortException e)
            {
                
// Another thread has signalled that this worker
                
// thread must terminate.  Typically, this occurs when
                
// the main service thread receives a service stop 
                
// command.

                
// Write a trace line indicating that the worker thread
                
// is exiting.  Notice that this simple thread does
                
// not have any local objects or data to clean up.
                Common.WriteLog(@"C:\Vod.FileMonitorWindowsService.txt"" FileMonitorWindowsService:        ThreadAbortException " + DateTime.Now+" "+e.Message + "\n");
#if LOGEVENTS
                EventLog.WriteEntry(
"FileMonitorWindowsService.WorkerThread", DateTime.Now.ToLongTimeString() +
                    
" - Thread abort signaled.");
#endif
            }
#if LOGEVENTS

            EventLog.WriteEntry(
"FileMonitorWindowsService.WorkerThread",DateTime.Now.ToLongTimeString() +
                
" - Exiting the service worker thread.");
#endif

        }
    }
}
系统服务的一些惯例代码

posted on 2007-08-23 09:21  星星博客园  阅读(532)  评论(0编辑  收藏  举报

导航

立即注册PayPal并开始接受信用卡付款。