使用Topshelf 5步建立Windows 服務

來源:互聯網
上載者:User

使用Topshelf建立Windows 服務簡要的介紹了建立Windows服務的另一種方法,老外的一篇文章Create a .NET Windows Service in 5 steps with Topshelf通過5個步驟詳細的介紹使用使用Topshelf建立Windows 服務。Topshelf是一個開源的跨平台的宿主服務架構,支援Windows和Mono,只需要幾行代碼就可以構建一個很方便使用的服務宿主。

1、Topshelf的代碼託管在http://topshelf-project.com/,可以在這裡下載到最新的代碼。

2、使用Visual Studio建立一個控制台應用程式引用程式集TopShelf.dll 合log4net.dll 。

3、建立一個簡單的服務類,裡麵包含兩個方法Start和Stop,這個服務只是示範代碼,所以我們每隔5秒輸出一個日誌。

using System;
using System.Timers;
using log4net;

namespace SampleWindowsService
{
public class SampleService
{
private Timer _timer = null;
readonly ILog _log = LogManager.GetLogger(typeof(SampleService));

public SampleService()
{
double interval = 5000;
_timer = new Timer(interval);
_timer.Elapsed += new ElapsedEventHandler(OnTick);
}

protected virtual void OnTick(object sender, ElapsedEventArgs e)
{
_log.Debug("Tick:" + DateTime.Now.ToLongTimeString());
}

public void Start()
{
_log.Info("SampleService is Started");

_timer.AutoReset = true;
_timer.Enabled = true;
_timer.Start();
}

public void Stop()
{
_log.Info("SampleService is Stopped");

_timer.AutoReset = false;
_timer.Enabled = false;
}
}
}4、在Main方法中使用Topshelf宿主我們的服務,主要是告訴Topshelf如何設定我們的服務的配置和啟動和停止的時候的方法調用。

using System.IO;
using log4net.Config;
using Topshelf;

namespace SampleWindowsService
{
class Program
{
static void Main(string[] args)
{
XmlConfigurator.ConfigureAndWatch(
new FileInfo(".\\log4net.config"));

var host = HostFactory.New(x =>
{
x.EnableDashboard();
x.Service<SampleService>(s =>
{
s.SetServiceName("SampleService");
s.ConstructUsing(name => new SampleService());
s.WhenStarted(tc =>
{
XmlConfigurator.ConfigureAndWatch(
new FileInfo(".\\log4net.config"));
tc.Start();
});
s.WhenStopped(tc => tc.Stop());
});

x.RunAsLocalSystem();
x.SetDescription("SampleService Description");
x.SetDisplayName("SampleService");
x.SetServiceName("SampleService");
});

host.Run();
}
}
}
4、配置Log4net和運行我們的服務,服務可以當作控制台來運行,這在開發的時候是非常方便的。服務的安裝很方便SampleWindowsService.exe install安裝成功後,可以通過服務控制台啟動,或者也可以通過一下命令運行SampleWindowsService.exe start服務的卸載方法也非常簡單了SampleWindowsService.exe uninstall相關文章:使用Topshelf建立Windows 服務

A WCF calculator in a windows service with TopShelf

WCF service with Topshelf using as a host, log4net as logging tool, and HTML as output

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.