我正在使用 Microsoft 的新指南在 Visual Studio 2022 中創建 Windows 作業服務,以使用 BackgroundService使用 .Net Core 5.0 Windows Service創建Windows 服務。
我發現在安裝服務后,Background 類中沒有禁用停止按鈕的屬性(缺少 CanStop 屬性),就像我們在使用 .Net Framework 構建的本機 Windows 服務中所做的那樣。
是否有解決此問題的方法,或者他們是否會在即將發布的后臺服務版本中添加新功能?
uj5u.com熱心網友回復:
好吧,如果你打電話給UseWindowsService這種情況:
public static IHostBuilder UseWindowsService(this IHostBuilder hostBuilder)
{
return UseWindowsService(hostBuilder, _ => { });
}
...
public static IHostBuilder UseWindowsService(this IHostBuilder hostBuilder, Action<WindowsServiceLifetimeOptions> configure)
{
if (WindowsServiceHelpers.IsWindowsService())
{
// Host.CreateDefaultBuilder uses CurrentDirectory for VS scenarios, but CurrentDirectory for services is c:\Windows\System32.
hostBuilder.UseContentRoot(AppContext.BaseDirectory);
hostBuilder.ConfigureLogging((hostingContext, logging) =>
{
logging.AddEventLog();
})
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<IHostLifetime, WindowsServiceLifetime>();
services.Configure<EventLogSettings>(settings =>
{
if (string.IsNullOrEmpty(settings.SourceName))
{
settings.SourceName = hostContext.HostingEnvironment.ApplicationName;
}
});
services.Configure(configure);
});
}
return hostBuilder;
}
WindowsServiceLifetime實作ServiceBase具有以下屬性:
https://docs.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase.canstop?view=dotnet-plat-ext-6.0
所以也許你可以做這樣的事情:
var host = Host.CreateDefaultBuilder()
.UseWindowsService()
.Build();
var windowsServiceLifetime = host.Services.GetService<IHostLifetime>() as WindowsServiceLifetime;
// NOTE .Services.GetService<IHostLifetime>() will return IConsoleLifetime when running under console!
if (windowsServiceLifetime != null)
{
windowsServiceLifetime.CanStop = false;
}
我不確定這一點,但我做了一些調查,因此這篇文章。如果這不值錢,我會洗掉它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/395861.html
上一篇:TEdgeBrowser-OnNewWindowRequested-在另一個TEdgeBrowser中打開新視窗
