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.
This program sets up a handler for the Ctrl+C (SIGINT) signal. Here’s how it works:
We create a
ManualResetEvent
calleddone
. This will be used to signal when the program should exit.We set up an event handler for
Console.CancelKeyPress
. This event is raised when the user presses Ctrl+C.In the event handler, we print a message indicating that we’ve received an interrupt, then signal the
done
event.We set
eventArgs.Cancel = true
to prevent the process from terminating immediately, allowing us to perform any necessary cleanup.In the main thread, we wait for the
done
event to be signaled usingdone.WaitOne()
.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.
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.