gpt4 book ai didi

c# - TPL 数据流和控制台应用程序不会终止应用程序

转载 作者:行者123 更新时间:2023-11-30 21:53:05 28 4
gpt4 key购买 nike

我有一个应该批量调用并压缩大文件的控制台应用程序,我想使用 DataFlow,除了完成之外一切正常

请考虑以下代码

public static void CompressFiles(string folder)
{
var bufferBlock = new BufferBlock<FileInfo>();

bufferBlock.LinkTo(Target(), new DataflowLinkOptions() { PropagateCompletion = true});
var files = GetFilesFromFolder(folder);

Parallel.ForEach(files, file =>
{
bufferBlock.Post(file);
});

Stopwatch sw = new Stopwatch();

sw.Start();
Parallel.ForEach(files, file =>
{
CreateFileT(file.FullName);
});

sw.Stop();

// Task.WaitAll(bufferBlock.Completion);

bufferBlock.Completion.Wait();
string tempoImpiegato =
$"[Generatore PDZ] : tempo impiegato per la generazione di {files.Length} pdz : {sw.Elapsed}";

LogManager.GetLogger("normal").Info(tempoImpiegato);
}

和压缩 ActionBlock 是

private static ActionBlock<FileInfo> Target()
{
return new ActionBlock<FileInfo>(file =>
{
FileInfo bolFileName = new FileInfo(file.FullName.Replace($"{ApplicationHelper.FileExtensionPdf}", $"{ApplicationHelper.FileExtensionBOL}"));
FileInfo zipFileName = new FileInfo(file.FullName.Replace($"{ApplicationHelper.FileExtensionPdf}", $"{ApplicationHelper.FileExtensionPdz}"));

if (!File.Exists(file.FullName) || !File.Exists(bolFileName.FullName))
{
string s = $"File {file.FullName} o {bolFileName.FullName} non esistenti o inaccessibili";
Log.Warning(s);
}
else
{
try
{
using (ZipOutputStream s = new ZipOutputStream(zipFileName.OpenWrite()))
{
s.SetLevel(9);

ZipEntry entry1 = new ZipEntry(file.Name);
ZipEntry entry2 = new ZipEntry(bolFileName.Name);

entry1.Size = file.Length;
entry2.Size = bolFileName.Length;

byte[] buffer = ReadBytesFromFileInfo(file);
byte[] bufferBol = ReadBytesFromFileInfo(bolFileName);

s.PutNextEntry(entry1);
s.Write(buffer,0,buffer.Length);
s.PutNextEntry(entry2);
s.Write(bufferBol, 0, bufferBol.Length);
}
}
catch (Exception ex)
{
Log.Error(ex, "");
}
}
});
}

使用 bufferBlock.Completion.Wait() 会阻止程序,而不会继续...我将 PropagateCompletion 设置为 true 并且 Target() 有效(它生成文件)

最佳答案

您正在等待完成,但您并未发出完成信号。 BufferBlock 正在等待更多项目,它不知道您不会再向其中发送任何项目。

要发出完成信号,您需要在等待完成之前调用 Complete:

block.Complete();
await block.Completion;

关于c# - TPL 数据流和控制台应用程序不会终止应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34221755/

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