zoukankan      html  css  js  c++  java
  • Windows 服务开发框架介绍

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

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

    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");
                });
            }
        }
    }

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

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

    SampleWindowsService.exe install

    启动

    SampleWindowsService.exe start

    如果要卸载也很方便

    SampleWindowsService.exe uninstall

    效果如下:

    最后 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

    谢谢浏览!

  • 相关阅读:
    webapi之fiddler头设置
    ios---setContentOffset
    webapi参数处理get过个参数
    socket网络编程
    logging模块
    configparser模块(拷贝)
    hashlib模块--摘要算法
    异常处理
    面向对象拓展
    反射
  • 原文地址:https://www.cnblogs.com/Music/p/topshelf-1.html
Copyright © 2011-2022 走看看