简体   繁体   English

无法将工作人员服务启动为 windows 服务

[英]Can't start worker service as windows service

So.所以。 I created a worker service and want to run it as windows service.我创建了一个辅助服务并希望将其作为 windows 服务运行。 It works locally.它在本地工作。 I installed it to windows server via powershell new-service command.我通过 powershell new-service 命令将它安装到 windows 服务器。 When I start it via Services, it attempts to start, waits for 30 seconds (with loading bar progressing) and fails.当我通过服务启动它时,它会尝试启动,等待 30 秒(加载栏正在运行)并失败。 In event viewer I see generic errors:在事件查看器中,我看到一般错误:

  1. A timeout was reached (30000 milliseconds) while waiting for the MyService service to connect.等待 MyService 服务连接时超时(30000 毫秒)。
  2. The MyService service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion.由于以下错误,MyService 服务无法启动:该服务未及时响应启动或控制请求。

Now, the weird thing is, I added some logging to service logic, and it actually does needed stuff, windows just fails to start it, ie service does not respond to start, but works (for 30 seconds, after that server kills it because it gave no response for start).现在,奇怪的是,我在服务逻辑中添加了一些日志记录,它实际上确实需要一些东西,windows 只是无法启动它,即服务没有响应启动,但工作(持续 30 秒,在服务器杀死它之后因为它对开始没有任何反应)。 How do I fix it?我如何解决它? My Program.cs:我的程序.cs:

    public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            File.AppendAllText("templogs.txt", ex.Message + "\r\n");
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureServices((hostContext, services) =>
            {
                IConfiguration configuration = hostContext.Configuration;
                services.AddHostedService<Worker>();
                services.AddScoped<IActionHandler, ActionHandler>();
                services.AddScoped<IHttpHandler, HttpHandler>();
                services.AddDbContext<DbContext>(options =>
                {
                    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
                });
                File.AppendAllText("templogs.txt", "context registered\r\n");

            });
}

Worker service:工人服务:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly List<string> _inactiveStatuses;
    private readonly IServiceProvider _services;
    private readonly string _connectionString;


    public Worker(ILogger<Worker> logger, IConfiguration config, IServiceProvider services)
    {
        try
        {
            _logger = logger;
            _inactiveStatuses = config.GetSection("InactiveStatuses").GetChildren().Select(a => a.Value).ToList();
            _services = services;
            _connectionString = config.GetConnectionString("DefaultConnection");
        }
        catch (Exception ex)
        {
            File.AppendAllText("templogs.txt", ex.Message + "\r\n");
        }
    }
    public override async Task StartAsync(CancellationToken cancellationToken)
    {
        await base.StartAsync(cancellationToken);
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        await base.StopAsync(cancellationToken);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            using (var scope = _services.CreateScope())
            {
                File.AppendAllText("templogs.txt", "scope created\r\n");

                var actionHandler =
               scope.ServiceProvider
                   .GetRequiredService<IActionHandler>();
                var dbContext = scope.ServiceProvider.GetRequiredService<DbContext>();
                var activeStatuses = dbContext.Statuses.Where(a => !_inactiveStatuses.Contains(a.Name)).ToDictionary(a => a.Id, a => a.Name);
                List<Guid> activeStatusGuids = activeStatuses.Keys.ToList();
                while (!stoppingToken.IsCancellationRequested)
                {
                    File.AppendAllText("templogs.txt", "while strated\r\n");
                    //some logic
                    File.AppendAllText("templogs.txt", "first cycle\r\n");

                    await Task.Delay(1000, stoppingToken);
                }
            }
        }
        catch (Exception ex)
        {
            File.AppendAllText("templogs.txt", ex.Message + "\r\n");
        }
    }
}

Since I dont know the powershell new-service command that you used to create the windows service, I will assume, for the sake of this answer, that the problem is related to one I had.由于我不知道您用来创建 windows 服务的 powershell new-service 命令,因此为了这个答案,我假设该问题与我遇到的问题有关。

In my case I used the Windows Command Prompt to create and start a service called Worker.Service .在我的例子中,我使用 Windows 命令提示符创建并启动了一个名为Worker.Service的服务。

Here's how I ran into the The service did not respond to the start or control request in a timely fashion.以下是我遇到The service did not respond to the start or control request in a timely fashion. error:错误:

sc create Worker.Service binPath="C:\Users\<user.name>\source\repos\<repo>\Worker.Service\bin\Debug\netcoreapp3.1\Worker.Service.dll"

sc start Worker.Service

Here's the correct way to start it:这是启动它的正确方法:

sc create Worker.Service binPath="C:\Users\<user.name>\source\repos\<repo>\Worker.Service\bin\Debug\netcoreapp3.1\Worker.Service.exe"

sc start Worker.Service

The binPath can be obtained via Visual Studio's build output window. However make sure you use the .exe file and not the .dll file to register the service. binPath可以通过 Visual Studio 的构建 output window 获得。但是请确保使用.exe文件而不是.dll文件来注册服务。

This not an answer, but I do not have enough reputation to make a comment yet.这不是答案,但我还没有足够的声誉发表评论。 I am experiencing the exact same issue.我遇到了完全相同的问题。 Did you find a solution to your problem?你找到解决问题的方法了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM