Skip to content

Instantly share code, notes, and snippets.

@kuznero
Last active May 18, 2021 18:13
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kuznero/73acdadd8328383ea7d5 to your computer and use it in GitHub Desktop.
Save kuznero/73acdadd8328383ea7d5 to your computer and use it in GitHub Desktop.
Console application that exit on Ctrl-C (ready for Docker)

Console application that exit on Ctrl-C (ready for Docker)

Console.ReadLine or Console.ReadKey do not work as expected under Docker container environment. Thus, typical way to solve this would be to properly handle Ctrl-C key combination.

C# snippet

using System;
using System.Threading;
using System.Threading.Tasks;

namespace TestConsole
{
  public class Prorgam
  {
    private static readonly AutoResetEvent _closing = new AutoResetEvent(false);

    public static void Main(string[] args)
    {
      Task.Factory.StartNew(() => {
        while (true)
        {
          Console.WriteLine(DateTime.Now.ToString());
          Thread.Sleep(1000);
        }
      });
      Console.CancelKeyPress += new ConsoleCancelEventHandler(OnExit);
      _closing.WaitOne();
    }

    protected static void OnExit(object sender, ConsoleCancelEventArgs args)
    {
      Console.WriteLine("Exit");
      _closing.Set();
    }
  }
}

F# snippet

open System
open System.Threading
open System.Threading.Tasks

let rec loop () =
  Console.WriteLine (DateTime.Now.ToString())
  Thread.Sleep (1000)
  loop ()

[<EntryPoint>]
let main argv =
  Task.Factory.StartNew(fun () -> loop ()) |> ignore
  let closing = new AutoResetEvent(false)
  let onExit = new ConsoleCancelEventHandler(fun _ args -> Console.WriteLine("Exit"); closing.Set() |> ignore)
  Console.CancelKeyPress.AddHandler onExit
  closing.WaitOne() |> ignore
  0
@mmetesreau
Copy link

Thanks, another way is to use unix termination signals as described here

@haf
Copy link

haf commented Jul 23, 2019

Note that in your example, you're not cancelling the task, only making the application exit and the CLR handle the termination of the task threads.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment