一个.NET 自身的系统服务框架,可以方便的用控制台进行开发,命令启动

TopShelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主。

vs 创建控制台项目 Nuget 引入

Install-Package Topshelf

实例代码

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace TopShelfDemo
{
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<Test>(s =>
{
s.ConstructUsing(name => new Test());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();

x.SetDescription("任务描述信息");
x.SetDisplayName("TestServer");
x.SetServiceName("TestServer");

x.OnException(ex =>
{
new Test().Ex(ex.Message);
});
});
}
}
}
/// <summary>
/// 测试
/// </summary>
public class Test
{
public string LogPath { get { return Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "log.txt"); } }
public void Start()
{
Task.Run(() =>
{
var times = 0;
while (true)
{
if (times > 1000)
{
throw new Exception("运行次数超过1000");
}
File.AppendAllText(LogPath, $"{DateTime.Now.ToString()} 运行次数{times + 1} " + Environment.NewLine);
times++;
Thread.Sleep(1000);
}
});
}
public void Stop()
{
Task.Run(() =>
{
File.AppendAllText(LogPath, $"{DateTime.Now.ToString()} 服务停止! " + Environment.NewLine);
});
}
public void Ex(string ex)
{
Task.Run(() =>
{
File.AppendAllText(LogPath, $"{DateTime.Now.ToString()}: 服务异常:{ex} " + Environment.NewLine);
});
}
}

以上是测试实例

服务启动命令

安装:TopShelfDemo.exe install
启动:TopShelfDemo.exe start
卸载:TopShelfDemo.exe uninstall