在.NET中启动Windows背景服务的参数

发布于 2025-02-10 06:08:06 字数 328 浏览 2 评论 0原文

我正在使用.NET的backgroundService摘要类制作Windows服务(类似于 Microsoft撰写的本教程),但我似乎无法弄清楚如何使用Windows Services应用程序开始使用Windows Services应用程序传递给服务的参数。有人可以告诉我如何获得我在那里经历的论点还是我应该做什么?

I am making a Windows Service using .NET's BackgroundService abstract class (similar to the one in this tutorial by Microsoft) but I can't seem to figure out how to get start arguments passed to the service using the Windows Services app. Can someone tell me how to get the arguments I pass in there or what I should be doing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘虞初梦 2025-02-17 06:08:06

您必须从main

public static async Task Main(string[] args)
{
    IHost host = Host.CreateDefaultBuilder(args)
        .ConfigureLogging(options =>
        {
            options.ClearProviders();
            options.AddEventLog();
            options.AddConsole();
        })
        .UseWindowsService(options =>
        {
            options.ServiceName = "WorkerServiceTestArgs";
        })
        .ConfigureServices(services =>
        {
            services.AddSingleton(new MyArgsService(args));
            services.AddHostedService<Worker>();
        })
        .Build();

    await host.RunAsync();
}

您的工作人员对您的服务有一个依赖性:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly MyArgsService _myArgsService;

    public Worker(ILogger<Worker> logger, MyArgsService myArgsService)
    {
        _logger = logger;
        _myArgsService = myArgsService;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            _logger.LogInformation("Args: {args}", string.Join(";", _myArgsService.GetArgs()));

            await Task.Delay(1000, stoppingToken);
        }
    }
}

EG使用此简单服务:

public class MyArgsService
{
    private readonly string[] _args;

    public MyArgsService(string[] args)
    {
        _args = args;
    }

    public string[] GetArgs()
    {
        return _args;
    }
}

<

a href =“ https://i.sstatic.net/ qm3si.png“ rel =“ noreferrer”> “

i.sstatic.net/umk9b.png“ rel =“ noreferrer”> “

You have to pass through the args from Main:

public static async Task Main(string[] args)
{
    IHost host = Host.CreateDefaultBuilder(args)
        .ConfigureLogging(options =>
        {
            options.ClearProviders();
            options.AddEventLog();
            options.AddConsole();
        })
        .UseWindowsService(options =>
        {
            options.ServiceName = "WorkerServiceTestArgs";
        })
        .ConfigureServices(services =>
        {
            services.AddSingleton(new MyArgsService(args));
            services.AddHostedService<Worker>();
        })
        .Build();

    await host.RunAsync();
}

Your worker then has a dependency on your service:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly MyArgsService _myArgsService;

    public Worker(ILogger<Worker> logger, MyArgsService myArgsService)
    {
        _logger = logger;
        _myArgsService = myArgsService;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            _logger.LogInformation("Args: {args}", string.Join(";", _myArgsService.GetArgs()));

            await Task.Delay(1000, stoppingToken);
        }
    }
}

e.g. with this simple Service:

public class MyArgsService
{
    private readonly string[] _args;

    public MyArgsService(string[] args)
    {
        _args = args;
    }

    public string[] GetArgs()
    {
        return _args;
    }
}

Results:

Windows service config

Event log

治碍 2025-02-17 06:08:06

创建一个从servicebase派生的类以接收参数并实现ihostlifetime

public class MyServiceLifetime : ServiceBase, IHostLifetime
{
    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
    }

    public public Task WaitForStartAsync(CancellationToken cancellationToken)
        => Task.CompletedTask;
    
    public Task StopAsync(CancellationToken cancellationToken)
        => Task.CompletedTask;
}

useWindowsService替换此类。

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddSingleton<IHostLifetime, MyServiceLifetime>();
        services.AddSingleton<JokeService>();
        services.AddHostedService<WindowsBackgroundService>();
    })
    .Build();

Create a class derived from ServiceBase to receive parameters and implement IHostLifetime.

public class MyServiceLifetime : ServiceBase, IHostLifetime
{
    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
    }

    public public Task WaitForStartAsync(CancellationToken cancellationToken)
        => Task.CompletedTask;
    
    public Task StopAsync(CancellationToken cancellationToken)
        => Task.CompletedTask;
}

Replace this class with UseWindowsService.

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddSingleton<IHostLifetime, MyServiceLifetime>();
        services.AddSingleton<JokeService>();
        services.AddHostedService<WindowsBackgroundService>();
    })
    .Build();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文