我编写了一个 TopShelf 服务/控制台应用程序,它似乎按预期运行,除了我希望它在启动时运行一次,然后禁用自身直到下一次启动/重新启动。
我希望这会奏效:
class MyServiceClass
{
public void Start()
{
// do the things that need doing
this.Stop();
}
public void Stop()
{
}
但这不起作用,大概是因为 this.Stop() 命令用于清理,而不是导致服务停止。
我的 Program.cs 看起来像这样:
// Uses Topshelf: http://topshelf-project.com/
// Guided by: http://www.ordina.nl/nl-nl/blogs/2013/maart/building-windows-services-with-c-and-topshelf/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Topshelf;
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
HostFactory.Run(hostConfigurator =>
{
hostConfigurator.Service<MyServiceClass>(serviceConfigurator =>
{
serviceConfigurator.ConstructUsing(() => new MyServiceClass());
serviceConfigurator.WhenStarted(myServiceClass => myServiceClass.Start());
serviceConfigurator.WhenStopped(myServiceClass => myServiceClass.Stop());
});
hostConfigurator.RunAsLocalSystem();
hostConfigurator.SetDisplayName("MyService");
hostConfigurator.SetDescription("Does stuff.");
hostConfigurator.SetServiceName("MyService");
hostConfigurator.StartAutomatically();
hostConfigurator.EnableShutdown();
});
}
};
}
如何在执行结束时停止服务?
更新:根据 Damien 的意见,我现在有:
public class MyServiceClass
{
private readonly Task task;
private HostControl hostControl;
public MyServiceClass()
{
task = new Task(DoWork);
}
private void DoWork()
{
Console.WriteLine("Listen very carefully, I shall say this only once");
hostControl.Stop();
}
public void Start(HostControl hostControl)
{
// so we can stop the service at the end of the check
this.hostControl = hostControl;
// start the DoWork thread
task.Start();
}
public void Stop()
{
}
};
和更新的 Program.cs
class Program
{
static void Main(string[] args)
{
HostFactory.Run(hostConfigurator =>
{
hostConfigurator.Service<MyServiceClass>((serviceConfigurator =>
{
serviceConfigurator.ConstructUsing(() => new MyServiceClass());
serviceConfigurator.WhenStarted((myServiceClass, hostControl) => myServiceClass.Start(hostControl));
serviceConfigurator.WhenStopped(myServiceClass => myServiceClass.Stop());
}); /* compiler thinks there's a ")" missing from this line */
hostConfigurator.RunAsLocalSystem();
hostConfigurator.SetDisplayName("MyService");
hostConfigurator.SetDescription("Does stuff.");
hostConfigurator.SetServiceName("MyService");
hostConfigurator.StartAutomatically();
hostConfigurator.EnableShutdown();
});
}
};
但是,这不会编译。我的编译器建议在我的注释上(或周围)缺少“)”(如上面的代码所示),但添加右括号只会添加到错误列表中。
我觉得我很接近了……有什么想法吗?