Windows 服務開發架構介紹 - Topshelf

來源:互聯網
上載者:User

標籤: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。第三步:貼出下面的代碼。
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

謝謝瀏覽!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.