gpt4 book ai didi

c# - 只有 1 个进程显示事件并行 foreach

转载 作者:行者123 更新时间:2023-12-04 23:33:57 25 4
gpt4 key购买 nike

所以我使用 Parallel.Foreach 是因为我想启动 4 个独特的进程,它们基本上做同样的事情。给视频加水印。

它的工作原理是它应该打开 4 个 ffmpeg.exe 并向每个窗口传递一个参数,以便一次为 4 个视频添加水印。
但是.. 这不是正在发生的事情,它打开了 4 个进程,但只有 1 个处于事件状态。不确定它是否尝试使用同一个 4 次或者它可能是什么,但我需要帮助。

当我关闭工作进程时,3 个不工作的进程仍然存在,直到我手动关闭它们。
这是一个视觉表示

pic1

这是第二张图片,显示了关闭工作时发生的情况



这是代码:

public void Watermark()
{
Console.WriteLine("Please enter the directory with the mp4 files: ");
string EntryPath = Console.ReadLine();

//Console.WriteLine("Please enter the directory with the mp4 files: ");
//string OutputPath = Console.ReadLine();

var psi = new ProcessStartInfo();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.FileName = "ffmpeg.exe";
int i = 0;

var videos = Directory.EnumerateFiles(EntryPath, "*.mp4");
Parallel.ForEach(videos, new ParallelOptions { MaxDegreeOfParallelism = 4 },
vid =>
{
try
{
//Maybe those processes are trying to work on the same file and can't access it?
//It's probably better to use the event Exited than WaitForExit
psi.Arguments = $"-i {vid} -i watermarker.png -threads 4 -filter_complex \"overlay = 275:350\" C:\\Users\\Developer\\Desktop\\Eh\\Watermarked{i}.mp4";
var p = Process.Start(psi);
p.WaitForExit();

Console.WriteLine($"{vid} is watermarked");
i++;
}
catch (Exception)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error parsing that file");
Console.ForegroundColor = ConsoleColor.White;
}

});
Console.ReadLine();

}

最佳答案

您的增量(i++)是错误的,因此所有进程都尝试输出到同一个文件(Watermarked0.mp4),因为 i在给定当前代码的情况下保持 0。您需要使用 Interlocked.Increment(ref i)像这样:

Parallel.ForEach(videos, new ParallelOptions { MaxDegreeOfParallelism = 4 },
vid =>
{
try
{
//Maybe those processes are trying to work on the same file and can't access it?
//It's probably better to use the event Exited than WaitForExit
psi.Arguments = $"-i {vid} -i watermarker.png -threads 4 -filter_complex \"overlay = 275:350\" C:\\Users\\Developer\\Desktop\\Eh\\Watermarked{Interlocked.Increment(ref i)}.mp4";
var p = Process.Start(psi);
p.WaitForExit();

Console.WriteLine($"{vid} is watermarked");
}
catch (Exception)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error parsing that file");
Console.ForegroundColor = ConsoleColor.White;
}

});
Console.ReadLine();

我怀疑这就是为什么只有一个进程处于事件状态的原因。但是您不能使用 Guid 或其他东西作为文件名的唯一部分来避免计数器,因为您不应该在 Parallel.ForEach 中共享状态?

另见 this问答。

关于c# - 只有 1 个进程显示事件并行 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48328047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com