docker container exits immediately even with Console.ReadLine() in a .NET Core console application

后端 未结 9 1621
一个人的身影
一个人的身影 2020-12-09 15:43

I am trying to run a .NET Core 1.0.0 console application inside a docker container.
When I run dotnet run command from inside the Demo folder on my machin

相关标签:
9条回答
  • 2020-12-09 16:05

    I'm using this approach:

    static async Task Main(string[] args)
    {
       // run code ..
    
       await Task.Run(() => Thread.Sleep(Timeout.Infinite));
    }
    
    0 讨论(0)
  • 2020-12-09 16:06

    If you switch your app to target .NET Core 2.0, you can use the Microsoft.Extensions.Hosting package to host a .NET Core console application by using the HostBuilder API to start/stop your application. Its ConsoleLifetime class would process the general application start/stop method.

    In order to run your app, you should implement your own IHostedService interface or inherit from the BackgroundService class, then add it to host context within ConfigureServices.

    namespace Microsoft.Extensions.Hosting
    {
        //
        // Summary:
        //     Defines methods for objects that are managed by the host.
        public interface IHostedService
        {
            // Summary:
            // Triggered when the application host is ready to start the service.
            Task StartAsync(CancellationToken cancellationToken);
    
            // Summary:
            // Triggered when the application host is performing a graceful shutdown.
            Task StopAsync(CancellationToken cancellationToken);
        }
    }
    

    Here's a sample hosted service:

    public class TimedHostedService : IHostedService, IDisposable
    {
        private readonly ILogger _logger;
        private Timer _timer;
    
        public TimedHostedService(ILogger<TimedHostedService> logger)
        {
            _logger = logger;
        }
    
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is starting.");
    
            _timer = new Timer(DoWork, null, TimeSpan.Zero, 
                TimeSpan.FromSeconds(5));
    
            return Task.CompletedTask;
        }
    
        private void DoWork(object state)
        {
            _logger.LogInformation("Timed Background Service is working.");
        }
    
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is stopping.");
    
            _timer?.Change(Timeout.Infinite, 0);
    
            return Task.CompletedTask;
        }
    
        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
    

    Then creating the HostBuilder and adding the service and other components (logging, configuration).

    public class Program
    {
        public static async Task Main(string[] args)
        {
            var hostBuilder = new HostBuilder()
                 // Add configuration, logging, ...
                .ConfigureServices((hostContext, services) =>
                {
                    // Add your services with depedency injection.
                });
    
            await hostBuilder.RunConsoleAsync();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 16:08

    I am not sure why Console.ReadLine(); doesn't block the main thread when running a .NET Core console app in a detached docker container, but the best solution is to register a ConsoleCancelEventHandler with the Console.CancelKeyPress event.

    Then you can instead block the main thread with a type of Threading WaitHandle and signal the release of the main thread when Console.CancelKeyPress is fired.

    A good example code can be found here: https://gist.github.com/kuznero/73acdadd8328383ea7d5

    0 讨论(0)
提交回复
热议问题