Skip to content

Instantly share code, notes, and snippets.

@cooclsee
Forked from kuznero/Ctrl-C-Console-App.md
Created January 31, 2018 01:58
Show Gist options
  • Save cooclsee/5d01564220f9ccb983022bbb252b735a to your computer and use it in GitHub Desktop.
Save cooclsee/5d01564220f9ccb983022bbb252b735a 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment