/// <summary> /// 运行部件驱动线程。 /// </summary> /// <param name="runningMode">运行模式。</param> public virtual void Run(RunningModes runningMode) { StopEvent.Reset(); if (_cancelTokenSource == null) { _cancelTokenSource = new CancellationTokenSource(); Task.Factory.StartNew(() => { try { Running(runningMode); LogHelper.Debug($"{Name}部件启动。"); } catch (OperationCanceledException) { //ignorl } catch (Exception ex) { LogHelper.Debug("设备驱动程序异常", ex); } }, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning) .ContinueWith(task => Clean()); } }
/// <summary> /// 运行部件驱动线程。 /// </summary> /// <param name="runningMode">运行模式。</param> public virtual void Run(RunningModes runningMode) { StopEvent.Reset(); if (_cancelTokenSource == null) { _cancelTokenSource = new CancellationTokenSource(); Task.Factory.StartNew(() => { try { Running(runningMode); log.Debug($"{Name}部件启动。"); } catch (OperationCanceledException ex2) { MessageBox.Show("yichang" + ex2.ToString()); //ignorl } catch (Exception ex) { log.Fatal("设备驱动程序异常", ex); MessageBox.Show("yichang" + ex.ToString()); } }, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning) .ContinueWith(task => Clean()); } }
private async Task ProcessQueue(Stream stream) { while (true) { await Task.WhenAny(DataAvailableEvent.WaitOneAsync(), StopEvent.WaitOneAsync()); if (!StopEvent.WaitOne(0)) { byte[] data; if (!DataQueue.TryDequeue(out data)) { Logger.Trace("Unable to deque element from Queue due to concurrency access"); } if (DataQueue.IsEmpty) { Logger.Trace("Writing queue is empty. Wait for new element..."); DataAvailableEvent.Reset(); } try { Logger.Trace("Write queue element {0}", data.GetHashCode()); await stream.WriteAsync(data, 0, data.Length); } catch (Exception e) { Logger.Debug(e, "Unable to send data"); QueueData(data); break; } } else { Logger.Trace("Queue is stopped"); StopEvent.Reset(); break; } } }
/// <summary> /// Start the service, autodetecting between Windows service and command line. Always blocks until service is stopped. /// </summary> public void Run(ServiceArguments argumentsOverride = null) { ServiceStoppedEvent = new TaskCompletionSource <object>(); Arguments = argumentsOverride ?? new ServiceArguments(Environment.GetCommandLineArgs().Skip(1).ToArray()); CurrentApplicationInfo.Init(ServiceName, Arguments.InstanceName, InfraVersion); if (Arguments.ProcessorAffinity != null) { int processorAffinityMask = 0; foreach (var cpuId in Arguments.ProcessorAffinity) { processorAffinityMask |= 1 << cpuId; } Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(processorAffinityMask); } if (Arguments.ServiceStartupMode == ServiceStartupMode.WindowsService) { Trace.WriteLine("Service starting as a Windows service..."); WindowsService = new DelegatingServiceBase(ServiceName, OnWindowsServiceStart, OnWindowsServiceStop); if (argumentsOverride == null) { Arguments = null; // Ensures OnWindowsServiceStart reloads parameters passed from Windows Service Manager. } ServiceBase.Run(WindowsService); // This calls OnWindowsServiceStart() on a different thread and blocks until the service stops. } else { if (Arguments.ShutdownWhenPidExits != null) { try { MonitoredShutdownProcess = Process.GetProcessById(Arguments.ShutdownWhenPidExits.Value); } catch (ArgumentException e) { Console.WriteLine($"Service cannot start because monitored PID {Arguments.ShutdownWhenPidExits} is not running. Exception: {e}"); Environment.ExitCode = 1; return; } Console.WriteLine($"Will perform graceful shutdown when PID {Arguments.ShutdownWhenPidExits} exits."); MonitoredShutdownProcess.Exited += (s, a) => { Console.WriteLine($"PID {Arguments.ShutdownWhenPidExits} has exited, shutting down..."); Stop(); }; MonitoredShutdownProcess.EnableRaisingEvents = true; } OnStart(); if (Arguments.ServiceStartupMode == ServiceStartupMode.CommandLineInteractive) { Thread.Sleep(10); // Allow any startup log messages to flush to Console. Console.Title = ServiceName; if (Arguments.ConsoleOutputMode == ConsoleOutputMode.Color) { Console.ForegroundColor = ConsoleColor.Green; Console.Write("Service initialized in interactive mode (command line). Press "); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.DarkCyan; Console.Write("[Alt+S]"); Console.ForegroundColor = ConsoleColor.Green; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(" to stop the service gracefully."); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.WriteLine("Service initialized in interactive mode (command line). Press [Alt+S] to stop the service gracefully."); } Task.Factory.StartNew(() => { while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.S && key.Modifiers == ConsoleModifiers.Alt) { Stop(); break; } } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } else { Console.WriteLine("Service initialized in non-interactive mode (command line). Waiting for stop request..."); } StopEvent.Reset(); ServiceStartedEvent.SetResult(null); StopEvent.WaitOne(); Console.WriteLine(" *** Shutting down... *** "); Task.Run(() => OnStop()).Wait(Arguments.OnStopWaitTime ?? TimeSpan.FromSeconds(10)); ServiceStartedEvent = new TaskCompletionSource <object>(); ServiceStoppedEvent.SetResult(null); MonitoredShutdownProcess?.Dispose(); if (Arguments.ServiceStartupMode == ServiceStartupMode.CommandLineInteractive) { if (Arguments.ConsoleOutputMode == ConsoleOutputMode.Color) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine(" *** Shutdown complete. Press any key to exit. *** "); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Gray; } else { Console.WriteLine(" *** Shutdown complete. Press any key to exit. *** "); } Console.ReadKey(true); } } }
/// <summary> /// Start the service, auto detecting between Windows service and command line. Always blocks until service is stopped. /// </summary> public void Run(ServiceArguments argumentsOverride = null) { ServiceGracefullyStopped = new TaskCompletionSource <StopResult>(); try { Arguments = argumentsOverride ?? new ServiceArguments(System.Environment.GetCommandLineArgs().Skip(1).ToArray()); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ServiceArguments.GetHelpDocumentation()); return; } if (argumentsOverride == null && ServiceArguments.IsHelpRequired(System.Environment.GetCommandLineArgs())) { Console.WriteLine(ServiceArguments.GetHelpDocumentation()); return; } if (Arguments.ServiceStartupMode == ServiceStartupMode.WindowsService) { Trace.WriteLine("Service starting as a Windows service..."); WindowsService = new DelegatingServiceBase(ServiceName, OnWindowsServiceStart, OnWindowsServiceStop); if (argumentsOverride == null) { Arguments = null; // Ensures OnWindowsServiceStart reloads parameters passed from Windows Service Manager. } ServiceBase.Run(WindowsService); // This calls OnWindowsServiceStart() on a different thread and blocks until the service stops. } else if (Arguments.ServiceStartupMode == ServiceStartupMode.VerifyConfigurations) { OnVerifyConfiguration(); } else { if (Arguments.ShutdownWhenPidExits != null) { try { MonitoredShutdownProcess = Process.GetProcessById(Arguments.ShutdownWhenPidExits.Value); } catch (ArgumentException e) { Console.WriteLine($"Service cannot start because monitored PID {Arguments.ShutdownWhenPidExits} is not running. Exception: {e}"); System.Environment.ExitCode = 1; ServiceGracefullyStopped.SetResult(StopResult.None); return; } Console.WriteLine($"Will perform graceful shutdown when PID {Arguments.ShutdownWhenPidExits} exits."); MonitoredShutdownProcess.Exited += (s, a) => { Console.WriteLine($"PID {Arguments.ShutdownWhenPidExits} has exited, shutting down..."); Stop(); }; MonitoredShutdownProcess.EnableRaisingEvents = true; } try { OnStart(); } catch (Exception e) { ServiceStartedEvent.TrySetException(e); throw; } if (Arguments.ServiceStartupMode == ServiceStartupMode.CommandLineInteractive) { Thread.Sleep(10); // Allow any startup log messages to flush to Console. Console.Title = ServiceName; if (Arguments.ConsoleOutputMode == ConsoleOutputMode.Color) { Console.ForegroundColor = ConsoleColor.Green; Console.Write("Service initialized in interactive mode (command line). Press "); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.DarkCyan; Console.Write("[Alt+S]"); Console.ForegroundColor = ConsoleColor.Green; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(" to stop the service gracefully."); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.WriteLine("Service initialized in interactive mode (command line). Press [Alt+S] to stop the service gracefully."); } Task.Factory.StartNew(() => { while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.S && key.Modifiers == ConsoleModifiers.Alt) { Stop(); break; } } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } else { Console.WriteLine("Service initialized in non-interactive mode (command line). Waiting for stop request..."); } StopEvent.Reset(); ServiceStartedEvent.SetResult(null); StopEvent.WaitOne(); Console.WriteLine(" *** Shutting down... *** "); var maxShutdownTime = TimeSpan.FromSeconds((Arguments.OnStopWaitTimeSec ?? 0) + (Arguments.ServiceDrainTimeSec ?? 0)); bool isServiceGracefullyStopped = Task.Run(() => OnStop()).Wait(maxShutdownTime); if (isServiceGracefullyStopped == false) { Console.WriteLine($" *** Service failed to stop gracefully in the allotted time ({maxShutdownTime}), continuing with forced shutdown. *** "); } ServiceStartedEvent = new TaskCompletionSource <object>(); ServiceGracefullyStopped.SetResult(isServiceGracefullyStopped ? StopResult.Graceful : StopResult.Force); MonitoredShutdownProcess?.Dispose(); if (Arguments.ServiceStartupMode == ServiceStartupMode.CommandLineInteractive) { if (Arguments.ConsoleOutputMode == ConsoleOutputMode.Color) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine(" *** Shutdown complete. Press any key to exit. *** "); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Gray; } else { Console.WriteLine(" *** Shutdown complete. Press any key to exit. *** "); } Console.ReadKey(true); } } }
/// <summary> /// Start the service, autodetecting between Windows service and command line. Always blocks until service is stopped. /// </summary> public void Run(ServiceArguments argumentsOverride = null) { ServiceGracefullyStopped = new TaskCompletionSource <StopResult>(); Arguments = argumentsOverride ?? new ServiceArguments(Environment.GetCommandLineArgs().Skip(1).ToArray()); CurrentApplicationInfo.Init(ServiceName, Arguments.InstanceName, InfraVersion); if (Arguments.ShutdownWhenPidExits != null) { try { MonitoredShutdownProcess = Process.GetProcessById(Arguments.ShutdownWhenPidExits.Value); } catch (ArgumentException e) { Console.WriteLine($"Service cannot start because monitored PID {Arguments.ShutdownWhenPidExits} is not running. Exception: {e}"); Environment.ExitCode = 1; ServiceGracefullyStopped.SetResult(StopResult.None); return; } Console.WriteLine($"Will perform graceful shutdown when PID {Arguments.ShutdownWhenPidExits} exits."); MonitoredShutdownProcess.Exited += (s, a) => { Console.WriteLine($"PID {Arguments.ShutdownWhenPidExits} has exited, shutting down..."); Stop(); }; MonitoredShutdownProcess.EnableRaisingEvents = true; } OnStart(); if (Arguments.ServiceStartupMode == ServiceStartupMode.CommandLineInteractive) { Thread.Sleep(10); // Allow any startup log messages to flush to Console. Console.Title = ServiceName; if (Arguments.ConsoleOutputMode == ConsoleOutputMode.Color) { Console.ForegroundColor = ConsoleColor.Green; Console.Write("Service initialized in interactive mode (command line). Press "); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.DarkCyan; Console.Write("[Alt+S]"); Console.ForegroundColor = ConsoleColor.Green; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(" to stop the service gracefully."); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.WriteLine("Service initialized in interactive mode (command line). Press [Alt+S] to stop the service gracefully."); } Task.Factory.StartNew(() => { while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.S && key.Modifiers == ConsoleModifiers.Alt) { Stop(); break; } } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } else { Console.WriteLine("Service initialized in non-interactive mode (command line). Waiting for stop request..."); } StopEvent.Reset(); ServiceStartedEvent.SetResult(null); StopEvent.WaitOne(); Console.WriteLine(" *** Shutting down... *** "); var maxShutdownTime = TimeSpan.FromSeconds(Arguments.OnStopWaitTimeSec ?? 0); bool isServiceGracefullyStopped = Task.Run(() => OnStop()).Wait(maxShutdownTime); if (isServiceGracefullyStopped == false) { Console.WriteLine($" *** Service failed to stop gracefully in the allotted time ({maxShutdownTime}), continuing with forced shutdown. *** "); } ServiceStartedEvent = new TaskCompletionSource <object>(); ServiceGracefullyStopped.SetResult(isServiceGracefullyStopped ? StopResult.Graceful : StopResult.Force); MonitoredShutdownProcess?.Dispose(); if (Arguments.ServiceStartupMode == ServiceStartupMode.CommandLineInteractive) { if (Arguments.ConsoleOutputMode == ConsoleOutputMode.Color) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine(" *** Shutdown complete. Press any key to exit. *** "); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Gray; } else { Console.WriteLine(" *** Shutdown complete. Press any key to exit. *** "); } Console.ReadKey(true); } }