0

I am trying to create a program that runs multiple processes in separate threads. The program should have two methods of termination: after a specified amount of time the program terminates, or a pre-defined key combination will kill it. I have the setup in the Main thread to sleep for the amount of time and then abort the threads, but I can't seem how to set up another thread to check for if at anytime the user presses a key combination

This is what I started for the termination:

killKeyThread = new Thread(new ThreadStart(KeyCombo));

[names of various threads].Start();

DateTime future = DateTime.Now.addSeconds(_totalDurationSeconds);
while (future > DateTime.Now)
{
    Thread.Sleep(1000);
}

[names of various threads].Abort();

I'm almost certain that the program needs to use a Windows Hooks in the thread, but I can't seem to set it up right.

Also if anyone has a better way of achieving this, it would be much appreciated

  • You mention Windows Hook; are you expecting the user to close the threads while they are not focused on the application? If not, you might be able to do this on a `KeyDown` event on your form. – EyeSeeSharp Apr 17 '15 at 16:27
  • 3
    Never use `Thread.Abort` if you're not sure what it is doing. Refer my related [answer here](http://stackoverflow.com/questions/27561976/check-if-thread-finished-its-method-before-killing-it-c-sharp/27562048#27562048) also my [related question here](http://stackoverflow.com/questions/18154164/how-does-thread-abort-work). Use cooperative cancellation. You do it using `CancellationToken`. – Sriram Sakthivel Apr 17 '15 at 16:28
  • To listen for a specific key combination: In Windows 7 and XP you can use RegisterHotKey https://msdn.microsoft.com/en-gb/library/windows/desktop/ms646309%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 but in Windows 8 that has been disabled and you have to hook into the keyboard events. – Ulric Apr 17 '15 at 16:29
  • @EyeSeeSharp The program is expected to normally be in the background as everything is running in the background which is why I mentioned using Windows Hook, but unfortunately I haven't successfully been able to set it up properly – victorfugazzotto Apr 17 '15 at 19:13

0 Answers0