1

我有这个压缩视频任务,它使用外部程序在 c# 中完成。完成此压缩并写出文件需要一些时间。在我知道外部操作有时间完成之前,我不想运行下一段代码。

我想做一个简单的 Thread.sleep(一些猜测);然后运行下一行代码还是有更好的方法?

这就是我压缩视频的方式:

 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;
        }

虽然我意识到我不确定这是否是在自己做一个进程/线程嗯。

4

4 回答 4

3

如果您使用的是新线程,则可以调用Thread.Join

Thread.Join(otherThread);

...可能超时。

在 .NET 4 中,您可以使用任务并行库(创建一个Taskor Task<TResult>),然后调用Wait. (如果您使用的是 .NET 4,TPL 绝对是一般的方式 - 您可以用它做很多事情。)

这两种方法都是阻塞的——它们会阻止等待线程做任何其他事情,直到另一个任务完成;这不是你想在 UI 线程中做的事情。因此,如果这是在用户界面的上下文中,最好使用回调来代替 - 让其他任务在完成后回调到 UI 线程;这可以启动下一段代码。

编辑:您显示的代码是创建一个新进程,而不是一个新线程。你也可能一个新线程中做这件事,但你还没有展示出来。目前还不清楚这一切是否都发生在 Windows 窗体或 WPF 等 UI 中,或者它是否只是一个控制台应用程序。

于 2011-09-01T05:30:11.387 回答
0

看看msdn:任务并行库

于 2011-09-01T05:30:26.567 回答
0
   Public void compressVideo(obkect o)
   {
      \\ code
    }

    Thread t = new Thread( new threathStart( \\ pass the method that you want to execute on this thread...
    t.start(parameterYouWishtoPas);
    while(t.IsAlive)
    {
       Thread.sleep(1);
     }
     \\ this line will not execute untill thread t finishes executing...
于 2011-09-01T05:40:03.437 回答
0

我不会做 Tano 建议的睡眠建议……没有理由仅仅为了等待另一个线程(忙等待)而占用 CPU。乔恩的建议就是你所需要的。

如果压缩线程由于某种原因永远不会结束,那么我建议您尝试使用reset events。看看这里

于 2011-09-01T05:53:07.923 回答