I am writing a Console app in C# 4 and want to gracefully cancel my program and Ctrl + C is pressed. The following code I have used many times before, but now when trying to use it in .NET 4, it seems a strange unhandled exception is occurring.
namespace ConsoleTest
{
class Program
{
private static bool stop = false;
static void Main(string[] args)
{
System.Console.TreatControlCAsInput = false;
System.Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
while (!stop)
{
System.Console.WriteLine("waiting...");
System.Threading.Thread.Sleep(1000);
}
System.Console.WriteLine("Press any key to exit...");
System.Console.ReadKey(true);
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
stop = true;
e.Cancel = true;
}
}
}
If I change the Target Framework to .NET 3.5, it works.
EDIT: It seems this person is seeing the same issue: http://johnwheatley.wordpress.com/2010/04/14/net-4-control-c-event-handler-broken/
The console is an operating system window where users interact with the operating system or with a text-based console application by entering text input through the computer keyboard, and by reading text output from the computer terminal.
Console. WriteLine("This is C#"); In this code line, we print the "This is C#" string to the console. To print a message to the console, we use the WriteLine method of the Console class.
Console class provides methods to access the character-based console device, if any, associated with the current Java virtual machine. The Console class was added to java.io by JDK 6. Important Points: It is used to read from and write to the console, if one exists.
This is a known issue on Microsoft Connect.
Note that it does work outside of the debugger.
For a console application under VS2010 and .NET 4.0, i am using the following (not very clean) workaround:
Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
{
if (e.SpecialKey == ConsoleSpecialKey.ControlC)
{
e.Cancel = true; // tell the CLR to keep running
}
else if (e.SpecialKey == ConsoleSpecialKey.ControlBreak)
{
//e.Cancel = true; // "Applications are not allowed to cancel the ....
}
// do whatever you must to inform threads on application exit, etc
}
Although not obvious, this code will allow you to debug your CTRL-C handler like so:
The debugger will ask you about this interruption, click [Ignore] and you will find yourself in the handler (make sure a breakpoint was set)
THE SAME code will execute if ctrl+c is pressed, the only difference is you must set e.Cancel to true.
As pointed out by everybody else, the problem DOES NOT exist at runtime, this workaround is ONLY for stepping through the handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With