c# - 执行当前文件夹下的所有.bat文件,执行后删除

标签 c# multithreading batch-file

我是一名想要制作平均视频的新手程序员。我已经制作了一个程序来创建 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 objectSystem.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/

相关文章:

c# - 在 Windows 8 应用程序中使用 HttpClient 的并行 HTTPRequest

c# - LVM_GETCOLUMN 只返回第一列的信息

c# - 在处理静态方法时将代码保持在同一级别

python - Google App Engine (GAE) 中的线程或后台进程

windows - 循环中的批处理脚本 "continue"?

C#极小极大树的实现

.net - 在 .Net 应用程序中管理来自单个 Socket 的并发读取

multithreading - 在 mod_perl 中使用线程

batch-file - 我的 goto 重定向不起作用,但可以使用 echo

batch-file - 如何在不隐藏控制台窗口的情况下运行批处理文件?