Skip to content
This repository has been archived by the owner on Sep 6, 2023. It is now read-only.

Commit

Permalink
Merge pull request #582 from tmaczynski/delete_thread_sleep3
Browse files Browse the repository at this point in the history
use ManualResetEventSlim instead of using Thread.Sleep in a loop
  • Loading branch information
JimBobSquarePants authored May 2, 2017
2 parents 8431a03 + 8a59731 commit fef7829
Showing 1 changed file with 29 additions and 37 deletions.
66 changes: 29 additions & 37 deletions src/ImageProcessor.Web.Plugins.PostProcessor/PostProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit fef7829

Please sign in to comment.