Reputation: 3333
Is it possible to set time limit for process? I realize that this can be done using multithreading. For instance I could use one thread that executes the process and an other thread that kills it after the some amount of time, but isn't there a more simple solution?
Upvotes: 0
Views: 3666
Reputation: 3070
You could spawn the process, wait a certain amount of time, and then kill it.
var proc = Process.Start("myproc.exe");
bool graceful = proc.WaitForExit(10000); //Wait 10 secs.
if (!graceful)
{
proc.Kill();
}
Upvotes: 1
Reputation: 42444
If you start the process you can as well schedule it with schtasks /create.
That will give you what you need almost for free (almost because your startup process is a little bit more complex, there are no free lunches)
SCHTASKS /Create /SC DAILY /TN gaming /TR c:\freecell /ST 12:00 /ET 14:00 /K
Knowledgebase article on schtasks
Upvotes: 0
Reputation: 972
Unless the thread that is executing can periodically check itself and exit gracefully, no. In most cases you cannot trust an executing thread to do this.
Upvotes: 0
Reputation: 437376
No, because such a solution would not know exactly how to stop the process after the time limit has elapsed. Killing the process outright is potentially dangerous stuff, so in the general case the process needs to cooperate for a graceful shutdown to be achieved.
It's really not that difficult to set up a timer and have your main loop check for a condition that signifies the timer has elapsed.
Upvotes: 1