<bdo id="vljxk"><rt id="vljxk"><noframes id="vljxk"><noframes id="vljxk"><noframes id="vljxk"><rt id="vljxk"></rt><rt id="vljxk"></rt><noframes id="vljxk"><rt id="vljxk"><delect id="vljxk"></delect></rt><noframes id="vljxk"><rt id="vljxk"></rt><noframes id="vljxk"><noframes id="vljxk"><rt id="vljxk"></rt>

當前位置:首頁 >  站長 >  編程技術 >  正文

.NET Core使用Topshelf方式創建Windows服務的全過程記錄

 2020-11-20 15:22  來源: 腳本之家   我來投稿 撤稿糾錯

  阿里云優惠券 先領券再下單

這篇文章主要給大家介紹了關于.NET Core使用Topshelf方式創建Windows服務的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

Topshelf是一個.NET Standard庫,它消除了在.NET Framework和.NET Core中創建Windows服務的那些麻煩。

安裝

Install-Package Topshelf

代碼

using System;
using System.Collections.Generic;
using System.Text;
using Topshelf;


namespace ConsoleApp2222
{
 public class LoggingService : ServiceControl
 {
  private void Log(string logMessage)
  {
   Console.WriteLine(logMessage);
  }


  public bool Start(HostControl hostControl)
  {
   Log("Starting");
   return true;
  }


  public bool Stop(HostControl hostControl)
  {
   Log("Stopping");
   return true;
  }
 }
}

在Program.cs文件的Main方法中

1、服務的名稱

2、服務是否自動啟動

3、服務崩潰之后的重啟時間

using System;
using Topshelf;


namespace ConsoleApp2222
{
 internal class Program
 {
  private static void Main(string[] args)
  {
   HostFactory.Run(x =>
   {
    x.Service<LoggingService>();
    x.EnableServiceRecovery(r => r.RestartService(TimeSpan.FromSeconds(10)));
    x.SetServiceName("TestService");
    x.StartAutomatically();
   }
  );
  }
 }
}

部署服務

ConsoleApp2222.exe install

ConsoleApp2222.exe start

調試服務

如果我們的服務代碼已經在Visual Studio中打開了,我們就可以直接啟動調試。Topshelf會模擬在控制臺中啟動服務。我們應該能在控制臺中看到以下的消息。

這確實符合了我們的需求。它啟動了我們的服務,并像真正的Windows服務一樣在后臺運行。我們可以像往常一樣設置斷點,基本上它遵循的流程和正常安裝的服務一樣。

我們可以通過ctrl+c, 來關閉我們的應用,但是在運行服務執行Stop方法之前,它是不能被關閉的,這使我們可以調試服務的關閉流程。與調試指令和配置標志相比,這要容易的多。

這里需要注意一個問題。如果你收到的以下內容的消息:

這意味著你嘗試調試的服務實際上已經作為Windows服務被安裝在系統中了,你需要停止(不需要卸載)這個正在運行的服務,才可以正常調試。

參考文檔

https://topshelf.readthedocs.io/en/latest/configuration/config_api.html

https://github.com/Topshelf/Topshelf

http://topshelf-project.com/

總結

到此這篇關于.NET Core使用Topshelf方式創建Windows服務的文章就介紹到這了,更多相關.NET Core用Topshelf創建Windows服務內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

來源:腳本之家

鏈接:https://www.jb51.net/article/198948.htm

申請創業報道,分享創業好點子。點擊此處,共同探討創業新機遇!

相關標簽
asp.net
Windows
.net開發

相關文章

熱門排行

信息推薦