执行当前文件夹中的所有.bat文件,并在执行后将其删除

时间:2017-07-05 14:37:19

标签: c# multithreading batch-file

我是一名想要制作平均视频的新手程序员。我已经创建了一个程序来创建n个.bat文件来处理n个图像的平均值,现在我想尽快执行它们。

.bat文件是独立的。 我在Windows环境中。

我已经看过C#多线程(threadpool,parrallel.for,parralel.foreach等),但是这些函数似乎都没有用。我并不觉得我是谁做错了。

Powershell有一个功能正在执行我想要的功能,但仅适用于其他powershell命令。

我现在的代码主要是: (完整解决方案https://github.com/Madsfoto/ParallelExecutionForEach

var paths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.bat"); // have a list of all .bat files in the current directory
System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false; // above is to not see the cmd window

            proc.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory(); // It's easier than having to specify where this program will be run.



Parallel.ForEach(paths, new ParallelOptions { MaxDegreeOfParallelism = 4 }, currentFile => // 4 is set because I have 4 cores to use
                {
                    proc.StartInfo.FileName = currentFile; // Set the currentfile as the one being executed. currentFile is the name of the .bat file to execute
    proc.Start(); // execute the .bat file
                        proc.WaitForExit();
                    File.Delete(currentFile);
                });

当我同时运行3-4个以上的进程时,我得到System.InvalidOperationException: No process is associated with this objectSystem.UnauthorizedAccessException

我怀疑是WaitForExit()给我带来了问题,但是没有调试它的技能。

我也看过Threading.Task,但我的技能还不够好用。

所以我追求的解决方案如下:

执行带有x行独立操作的1个输入文件或带有1个操作的x个文件,同时在编译或运行时设置y进程限制。
编程语言对我来说并不重要,尽管我的偏好是可以理解的C#。

(结果类似于https://www.youtube.com/watch?v=ph6-6bYTgs0,其中n帧平均在一起)

1 个答案:

答案 0 :(得分:0)

解决方案是移动

proc.Start(); // execute the .bat file
proc.WaitForExit();
try
{
   File.Delete(FileName);
}
catch
{
}

将代码放入其自己的函数中(使用簿记内容(定义proc等))。

File.Delete()是罪魁祸首,事实证明Parallel.ForEach中可能存在一个错误,但我无法可靠地重现它(试验会给出错误〜0.01%的时间),但是这种方式有效。它确实需要人们重新运行可执行文件,但这是我可以向用户推送的负担。

github链接已更新为工作版本。