我有一个.exe进程,我想等2个小时才能完成。但如果需要超过1个小时,我想调用一个函数来发送电子邮件状态,这比平时需要更长的时间。如果一个函数花费的时间超过了一定的时间,但没有退出进程并等待了整整2个小时,如何调用它?
我如何将流程称为
var proc = System.Diagnostics.Process.Start(exePath, parameterString);
var procExited = proc.WaitForExit(twohourinmilliseconds);
//do something here if taking longer than 1 hour but not quit?
int exitCode = proc.ExitCode;
您可以尝试使用async
版本的WaitForExit
-WaitForExitAsync(并使您也能执行async
例程(:
var proc = System.Diagnostics.Process.Start(exePath, parameterString);
// Delay for an hour (3_600_000 milliseconds)
Task delay = Task.Delay(3_600_000);
// Asynchronously wait for two possible outcomes:
// 1. process completion
// 2. delay (timeout) completion
if (delay == await Task.WhenAny(proc.WaitForExitAsync(), delay)) {
// 1 hour passed, but proc is still running
//TODO: Send notification here
}
else {
// process completed before 1 hour passed
}
如果您不想等待超过2小时(7_200_000
毫秒(,并且您想在1等待小时后发送消息:
var proc = System.Diagnostics.Process.Start(exePath, parameterString);
// We are going to cancel proc after 2 hours (== 7_200_000 milliseconds)
// for its completion
using (CancellationTokenSource cs = new CancellationTokenSource(7_200_000)) {
Task delay = Task.Delay(3_600_000, cs.Token);
Task exe = proc.WaitForExitAsync(cs.Token);
try {
if (delay == await Task.WhenAny(exe, delay)) {
// 1 hour passed, but proc is still running
//TODO: Send notification here
}
// Keep on waiting exe
await exe;
// proc succesfully completed; we are within 2 hours timeout
//TODO: implement normal flow here
}
catch (TaskCanceledException) {
// 2 hours passed, proc execution cancelled
//TODO: you pobably want to send another message here
}
}