private void Initialize(bool multipleServices) { if (!_initialized) { //Cannot register the service with NT service manatger if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (!multipleServices) { _status.serviceType = ServiceTypeOptions.SERVICE_TYPE_WIN32_OWN_PROCESS; } else { _status.serviceType = ServiceTypeOptions.SERVICE_TYPE_WIN32_SHARE_PROCESS; } _status.currentState = ServiceControlStatus.STATE_START_PENDING; _status.controlsAccepted = 0; _status.win32ExitCode = 0; _status.serviceSpecificExitCode = 0; _status.checkPoint = 0; _status.waitHint = 0; _mainCallback = new ServiceMainCallback(this.ServiceMainCallback); _commandCallback = new ServiceControlCallback(this.ServiceCommandCallback); _commandCallbackEx = new ServiceControlCallbackEx(this.ServiceCommandCallbackEx); _handleName = Marshal.StringToHGlobalUni(this.ServiceName); _initialized = true; } }
public ServiceInfo(ServiceControlCallbackEx commandControlDelegate) { CommandControlDelegate = commandControlDelegate; Status = new SERVICE_STATUS(); _handle = GCHandle.Alloc(Status); StatusPtr = GCHandle.ToIntPtr(_handle); }
public static IntPtr RegisterServiceCtrlHandlerExHook(string serviceName, ServiceControlCallbackEx callback, IntPtr userData) { var serviceInfo = new ServiceInfo(callback); _serviceCommands.Add(serviceName, serviceInfo); return(serviceInfo.StatusPtr); }
private void ServiceMainCallback(Int32 argCount, IntPtr argPointer) { //!!! 函数委托必须引着,避免GC回收导致PInvoke内部报错 _commandHandler = ServiceCommandCallbackEx; _statusHandle = RegisterServiceCtrlHandlerEx(_service.ServiceName, _commandHandler, IntPtr.Zero); if (ReportStatus(ServiceControllerStatus.StartPending, 3000)) { //!!! 不要在ServiceMain里面调用系统函数 ThreadPoolX.QueueUserWorkItem(ServiceQueuedMainCallback); } }
public WindowsServiceRunner(string serviceName, ThreadStart onStart, ThreadStart onStop) { _serviceName = serviceName; _onStart = onStart; _onStop = onStop; _status = new SERVICE_STATUS { controlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN, currentState = SERVICE_START_PENDING, win32ExitCode = 0, serviceSpecificExitCode = 0, checkPoint = 0, waitHint = 0, serviceType = SERVICE_WIN32_OWN_PROCESS, }; _mainCallback = new ServiceMainCallback(ServiceMain); _commandCallback = new ServiceControlCallbackEx(ServiceCommandCallbackEx); _serviceName = serviceName; }
public static extern IntPtr RegisterServiceCtrlHandlerEx(String serviceName, ServiceControlCallbackEx callback, IntPtr userData);