我创建了Windows服务。安装Installutil.exe成功,但当我按下开始按钮时出现进度条"开始",然后它停止在50%。我必须取消。取消服务工作完美后,但禁用启动,停止和pasue命令。如果我想停止服务,我必须卸载服务。可能是什么原因?
主要方法:
tsc -p ./server <-- /server/tsconfig.json is loaded
tsc -p ./client <-- /client/tsconfig.json is loaded
这是我的服务类:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new TelegramBotService()
};
ServiceBase.Run(ServicesToRun);
}
答案 0 :(得分:1)
OnStart 方法必须在10秒内完成,否则服务控制管理器会认为它已挂起。目前它无限期地等待RunBot任务完成。
我已经描述了good way to deal with this approach。这是我的 OnStart 方法,它启动服务的控制器线程:
// SCM requests service start using its own thread.
// This method must complete within 10 seconds of it
// starting. Otherwise the SCM diagnoses a hang.
protected override void OnStart(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.UnhandledExceptionFilter);
this.ThreadController = new Thread(new ThreadStart(ControllerThreadRunning));
this.ThreadController.Name = THREAD_NAME_CONTROLLER;
this.ThreadController.Start();
base.OnStart(args);
}
这是控制器线程:
// Invoked when the controller thread starts.
private void ControllerThreadRunning()
{
// And we're on our way.
while ( !this.ServiceStopRequested )
{
// Start real work and then block until that finishes or crashes.
var realWork = this.LaunchWorkAsync();
realWork.Wait();
// If SCM didn't request a service stop, the assumption is that
// the real work crashed and needs to be restarted.
if ( !this.ServiceStopRequested )
{
this.PauseControllerThread("Pause before restarting work cycle.", this.RestartDelay);
}
}
// This service will now stop.
this.Cleanup();
}
这会异步启动服务的实际工作:
// This method handles all ceremony around the real work of this service.
private async Task LaunchWorkAsync()
{
try
{
// Setup progress reporting.
var progressReport = new Progress<string>
(progressInfo => { this.AppLog.Information(progressInfo, "ServiceMain.LaunchWorkAsync"); });
var progress = progressReport as IProgress<string>;
// Launch time.
await Task.Factory.StartNew( () => this.DoWork(progress), TaskCreationOptions.LongRunning );
}
// Report any exception raised during the work cycle.
catch (Exception ex)
{
this.AppLog.Error(string.Concat("Work cycle crashed", Environment.NewLine,
ex.GetType().FullName, Environment.NewLine,
ex.Message, Environment.NewLine,
ex.StackTrace));
}
return;
}
这就是服务的真正工作所在:
// This is where this service's real work is done.
// The work cycles continuously until it's asked to stop.
// If the work crashes with an unhandled exception, the
// controller thread will restart it after an appropriate delay.
private void DoWork(IProgress<string> progress)
{
while (!this.ServiceStopRequested)
{
Thread.Sleep(5000); // Simulated work cycle.
progress.Report("Completed current cycle of work.");
}
}