首页 > Windows开发 > 详细

Windows 服务开发框架介绍 - Topshelf

时间:2014-05-10 00:58:32      阅读:550      评论:0      收藏:0      [点我收藏+]

关于 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。

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

bubuko.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<TimeReporter>(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");
            });
        }
    }
}
bubuko.com,布布扣

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

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

SampleWindowsService.exe install

启动

SampleWindowsService.exe start

如果要卸载也很方便

SampleWindowsService.exe uninstall

效果如下:

bubuko.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,布布扣,bubuko.com

Windows 服务开发框架介绍 - Topshelf

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!