Prepare a .Net Core Console App for Docker

Last week I had the luck to attend the Microsoft Azure OpenHack in Amsterdam. We spent two and a half days learning a lot about kubernetes, Azure Container Services, Azure Container Registry, Azure OMS and Minecraft!

In one of the challenges we decided to implement a sidecar container for logging purposes. So using .NET Core we created a console application with proper handling of the"Control+C" and"Control+Break" key shortcuts.

The following code shows you the structure of the console app we created and will help you Prepare a .Net Core Console App for Docker

 1using System;
 2using System.Threading;
 3using System.Threading.Tasks;
 4
 5namespace docker.controlc
 6{
 7    class Program
 8    {
 9        // AutoResetEvent to signal when to exit the application.
10        private static readonly AutoResetEvent waitHandle = new AutoResetEvent(false);
11
12        static void Main(string[] args)
13        {
14            // Fire and forget
15            Task.Run(() =>
16            {
17                var random = new Random(10);
18                while (true)
19                {
20                    // Write here whatever your side car applications needs to do.
21                    // In this sample we are just writing a random number to the Console (stdout)
22                    Console.WriteLine($"Loop = {random.Next()}");
23
24                    // Sleep as long as you need.
25                    Thread.Sleep(1000);
26                }
27            });
28
29            // Handle Control+C or Control+Break
30            Console.CancelKeyPress += (o, e) =>
31            {
32                Console.WriteLine("Exit");
33
34                // Allow the manin thread to continue and exit...
35                waitHandle.Set();
36            };
37
38            // Wait
39            waitHandle.WaitOne();
40        }
41    }
42}

Note that we are handling the Console.CancelKeyPress because Docker does not behave as expected if you use the typical Console.ReadKey method to make the application run until a key is pressed.

Get the code here .

Hope it helps!


Use PowerShell to Enable Azure Analysis Services Firewall
Use PowerShell to Enable and Automate Azure Analysis Services Backup
comments powered by Disqus