I have this compress video task that uses an external program to do it in c#. It takes some time for this compression to finish and the file to write out. I don’t want to run the next piece of code until I know the external operation has had time to finish.
Do I want to do a simple Thread.sleep(some guess); and then run the next line of code or is there a better way?
this is how I am doing the compressing of the video:
try
{
String finalCommand = "";
String thePath = System.IO.Path.GetDirectoryName(fileName);
finalCommand ="-i " + fileName + " -s 320x240 -b 300k -r 30 -f avi " + thePath + "\\C" + System.IO.Path.GetFileName(fileName);
System.Diagnostics.ProcessStartInfo ffmpegcmd = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\ffmpeg.exe",
"-i \"" + fileName + "\" -s 320x240 -b 300k -r 30 -f avi \"" + thePath + "\\C" + System.IO.Path.GetFileName(fileName) + "\"");
ffmpegcmd.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(ffmpegcmd);
LogUtil.writeLog("About to wait for FFMPEGCMD process");
p.WaitForExit();
success = true;
LogUtil.writeLog("FFMPEGCMD process exited perfectly!");
}
catch (Exception ex)
{
LogUtil.writeLog("ERROR compressing and using FFMPEG");
success = false;
}
though I realize I am not sure if this is doing a process/thread on its own hmm.
If you’re using a new thread, you can just call
Thread.Join:… possibly with a timeout.
In .NET 4 you can use the Task Parallel Library (creating a
TaskorTask<TResult>) and then callWait. (If you’re using .NET 4, the TPL is definitely the way to go in general – you can do lots of stuff with it.)Both of these approaches are blocking – they will stop the waiting thread from doing anything else until the other task has completed; this isn’t something you want to do in the UI thread. So if this is in the context of a user interface, it would be best to use a callback instead – make the other task call back into the UI thread when it’s done; that can kick off the next piece of code.
EDIT: The code you’ve shown is creating a new process, not a new thread. You may also be doing it in a new thread, but you haven’t shown that. It’s also still unclear whether this is all taking place in a UI such as Windows Forms or WPF, or whether it’s just a console app.