diff --git a/src/ImageProcessor.Web.Plugins.PostProcessor/PostProcessor.cs b/src/ImageProcessor.Web.Plugins.PostProcessor/PostProcessor.cs index a11cc5af4..e8fd77260 100644 --- a/src/ImageProcessor.Web.Plugins.PostProcessor/PostProcessor.cs +++ b/src/ImageProcessor.Web.Plugins.PostProcessor/PostProcessor.cs @@ -100,50 +100,42 @@ private static PostProcessingResultEventArgs RunProcess(string sourceFile, long return null; } - int elapsedTime = 0; - bool eventHandled = false; - Process process = null; - try - { - process = new Process + using (var processingFinished = new ManualResetEventSlim(false)) + { + Process process = null; + try { - StartInfo = start, - EnableRaisingEvents = true - }; + process = new Process + { + StartInfo = start, + EnableRaisingEvents = true + }; - process.Exited += (sender, args) => - { - result = new PostProcessingResultEventArgs(sourceFile, length); - process?.Dispose(); - eventHandled = true; - }; + process.Exited += (sender, args) => + { + result = new PostProcessingResultEventArgs(sourceFile, length); + process?.Dispose(); + processingFinished.Set(); + }; - process.Start(); + process.Start(); - // Wait for Exited event, but not more than 5 seconds. - const int sleepAmount = 100; - while (!eventHandled) + // Wait for processing to finish, but not more than 5 seconds. + const int MaxWaitTimeMs = 5000; + processingFinished.Wait(MaxWaitTimeMs); + } + catch (System.ComponentModel.Win32Exception ex) { - elapsedTime += sleepAmount; - if (elapsedTime > 5000) - { - break; - } + // Some security policies don't allow execution of programs in this way + ImageProcessorBootstrapper.Instance.Logger.Log(typeof(PostProcessor), ex.Message); - Thread.Sleep(sleepAmount); + return null; + } + finally + { + // Make sure we always dispose and release + process?.Dispose(); } - } - catch (System.ComponentModel.Win32Exception ex) - { - // Some security policies don't allow execution of programs in this way - ImageProcessorBootstrapper.Instance.Logger.Log(typeof(PostProcessor), ex.Message); - - return null; - } - finally - { - // Make sure we always dispose and release - process?.Dispose(); } return result;