Windows 服务开发框架介绍 - Topshelf

2020-11-24 08:22

阅读:721

标签:des   style   blog   class   code   java   

关于 TopShelf

Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.

 

示例

第一步:新建一个 C# 控制台应用程序。

第二步:用 Nuget 引用 TopShelf 和 Log4net。

第三步:贴出下面的代码。

soscw.com,搜素材
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

using Topshelf;
using Topshelf.Builders;
using Topshelf.Configurators;
using Topshelf.HostConfigurators;

namespace TopshelfStudy
{
    public sealed class TimeReporter
    {
        private readonly Timer _timer;
        public TimeReporter()
        {
            _timer = new Timer(1000) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("当前时间:{0}", DateTime.Now);
        }
        public void Start() { _timer.Start(); }
        public void Stop() { _timer.Stop(); }
    }

    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service(s =>
                {
                    s.ConstructUsing(settings => new TimeReporter());
                    s.WhenStarted(tr => tr.Start());
                    s.WhenStopped(tr => tr.Stop());
                });

                x.RunAsLocalSystem();

                x.SetDescription("定时报告时间");
                x.SetDisplayName("时间报告器");
                x.SetServiceName("TimeReporter");
            });
        }
    }
}
soscw.com,搜素材

第四步:编译、Release 生成。把 Release 文件夹 Copy 到 C 盘。

第五步:以管理员身份运行 cmd,安装、启动。

SampleWindowsService.exe install

启动

SampleWindowsService.exe start

如果要卸载也很方便

SampleWindowsService.exe uninstall

效果如下:

soscw.com,搜素材

 

最后 Windows Service 没有 Console.WriteLine,我们可以把输出信息输出到文件。

StreamWriter sw = new StreamWriter("e:\\temp\\log.log");
sw.AutoFlush = true;
Console.SetOut(sw);

参考网站:

http://www.cnblogs.com/shanyou/archive/2011/05/04/2037008.html

http://www.cnblogs.com/happyframework/p/3601995.html

http://www.cnblogs.com/chenxizhang/archive/2010/04/21/1716773.html

谢谢浏览!

Windows 服务开发框架介绍 - Topshelf,搜素材,soscw.com

Windows 服务开发框架介绍 - Topshelf

标签:des   style   blog   class   code   java   

原文地址:http://www.cnblogs.com/Music/p/topshelf-1.html


评论


亲,登录后才可以留言!