我是一名想要制作平均视频的新手程序员。我已经制作了一个程序来创建 n 个 .bat 文件,对 n 个图像进行平均处理,现在我想尽快执行它们。
.bat 文件是独立的。 我在 Windows 环境中。
我看过 C# 多线程(threadpool、parralel.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 object
和 System.UnauthorizedAccessException
。
我怀疑是 WaitForExit() 给我带来了问题,但我没有调试它的技能。
我也看过 Threading.Task,但我的技术不够好,无法使用它。
所以我的解决方案如下:
使用 x 行独立操作执行 1 个输入文件或使用 1 个操作执行 x 个文件,同时在编译或运行时设置 y 个进程限制。
编程语言对我来说并不重要,尽管我更喜欢可以理解的 C#。
(结果类似于 https://www.youtube.com/watch?v=ph6-6bYTgs0,n 帧一起平均)
最佳答案
解决方案是移动
proc.Start(); // execute the .bat file
proc.WaitForExit();
try
{
File.Delete(FileName);
}
catch
{
}
将代码写入它自己的函数(使用簿记内容(定义过程等))。
File.Delete() 是罪魁祸首,事实证明 Parallel.ForEach 中可能存在错误,但我一直无法可靠地重现它(实验大约有 0.01% 的时间会出错),但是这样就可以了。它确实需要人们重新运行可执行文件,但这是一种负担,我可以证明将其推给用户是合理的。
github链接已更新为可用版本。
关于c# - 执行当前文件夹下的所有.bat文件,执行后删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44929264/