C# .NET: how to pause and resume a program execution on a keypress?
it's a .NET non GUI application. It is specified as a console application, but the开发者_开发百科 console is not really used. what the application does is GUI testing of other applications
Others have described how you'd start/stop the problem execution ... for the actual key trapping, I'd suggest registering a global hotkey - but, you'd need to have a Windows form handle available to you, so I'd also suggest either launching your command-line utility from a GUI app, or simply including the functionality in a GUI app.
Is this kind of change possible?
EDIT: Christian Liensberger has made what looks like an excellent wrapper for this on his blog.
You would have to have your main thread waiting on Console.Read()
(or Console.ReadKey()
) all the time and do the actual work on another thread. When the main thread detects a keypress it needs to somehow notify the other thread to pause or resume (eg. using a WaitHandle
).
If the worker thread is doing something really simple and it's safe to suspend it at any time then you may be able to just suspend/resume the thread itself rather than doing any notifications.
Ok It Should look like this..
//Assuming the thread name given is 'newthread'
//First Start a thread
newthread.Start();
//use Console Key Class to read a key from keyboard
ConsoleKeyInfo cki = new ConsoleKeyInfo();
cki = Console.ReadKey(true);
//I am using letter 'p' to pause
if (cki.Key == ConsoleKey.P)
{
newthread.Suspend();
Console.WriteLine("Process Is Paused,Press 'Enter' to Continue...");
}
//Thread Resumption can only occur through another thread
//If the thread control has passed on to the main function
//resume it from there
// Resuming Thread if paused
if (newthread.ThreadState>0)
{
ConsoleKeyInfo ckm = new ConsoleKeyInfo();
ckm = Console.ReadKey(true);
if (ckm.Key == ConsoleKey.Enter)
{
Console.WriteLine("Resuming Process...");
newthread.Resume();
}
}
Note:This should work fine for now, but in reality you should synchronise your threads. When you will run the program then it will say that the pause and resume functions are obsolete. It will tell you to synchronise the threads.
精彩评论