Signals in C#

Here’s the translation of the Go code example to C# with explanations in Markdown format suitable for Hugo:

Our first example demonstrates how to handle signals in C#. This can be useful when you want your program to gracefully handle system signals, such as termination requests.

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // We'll use a ManualResetEvent to signal when the program should exit
        var done = new ManualResetEvent(false);

        // Set up the event handler for Ctrl+C
        Console.CancelKeyPress += (sender, eventArgs) =>
        {
            Console.WriteLine();
            Console.WriteLine("Interrupt received");
            done.Set(); // Signal that we're done
            eventArgs.Cancel = true; // Prevent the process from terminating immediately
        };

        Console.WriteLine("awaiting signal");
        done.WaitOne(); // Wait for the signal
        Console.WriteLine("exiting");
    }
}

This program sets up a handler for the Ctrl+C (SIGINT) signal. Here’s how it works:

  1. We create a ManualResetEvent called done. This will be used to signal when the program should exit.

  2. We set up an event handler for Console.CancelKeyPress. This event is raised when the user presses Ctrl+C.

  3. In the event handler, we print a message indicating that we’ve received an interrupt, then signal the done event.

  4. We set eventArgs.Cancel = true to prevent the process from terminating immediately, allowing us to perform any necessary cleanup.

  5. In the main thread, we wait for the done event to be signaled using done.WaitOne().

  6. Once the event is signaled (i.e., when Ctrl+C is pressed), the program continues and prints “exiting” before terminating.

When we run this program, it will block waiting for a signal. By pressing Ctrl+C, we can send an interrupt signal, causing the program to print “Interrupt received” and then exit.

$ dotnet run
awaiting signal
^C
Interrupt received
exiting

This approach allows for graceful shutdown of your C# applications, giving you the opportunity to clean up resources or save state before the program exits.

Note that while this example only handles Ctrl+C (SIGINT), C# and .NET provide ways to handle other types of signals as well, though the exact mechanism may differ depending on the operating system and the specific signal you’re interested in.