我有一堆ActionBlocks
,每个都做不同的事情。
TransformBlock
连续地馈入数据。ActionBlocks
只需在3个文本文件(日志)中写行。这很有效,除了3个日志记录ActionBlocks
仅在处理ActionBlock
完成后才开始使用数据(因此,它们在程序末尾一次性写入所有日志记录信息。
我想知道是否可以影响此行为,以便为日志记录ActionBlocks
赋予更高的优先级?
感谢您的帮助。
代码示例:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
namespace dataflowtest
{
class Program
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static readonly IReadOnlyCollection<string> charsSets = Enumerable.Repeat(chars, 8).ToList().AsReadOnly();
static readonly Random random = new Random();
static event EventHandler<string> MessageGot;
static async Task Main(string[] args)
{
var source = new TransformBlock<string, string>(GetMessage, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = -1, EnsureOrdered = false });
var target = new ActionBlock<string>(Console.WriteLine);
var programDir = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().GetName().CodeBase.Replace("file:///", ""));
using var file1 = new StreamWriter(Path.Combine(programDir, "file1.txt"));
using var file2 = new StreamWriter(Path.Combine(programDir, "file2.txt"));
using var file3 = new StreamWriter(Path.Combine(programDir, "file3.txt"));
var fileAction1 = new ActionBlock<string>(file1.WriteLineAsync);
var fileAction2 = new ActionBlock<string>(file2.WriteLineAsync);
var fileAction3 = new ActionBlock<string>(file3.WriteLineAsync);
MessageGot += async (_, e) => await fileAction1.SendAsync(e);
MessageGot += async (_, e) => await fileAction2.SendAsync(e);
MessageGot += async (_, e) => await fileAction3.SendAsync(e);
using (source.LinkTo(target, new DataflowLinkOptions { PropagateCompletion = true }))
{
for (int i = 0; i < 100; i++)
{
await source.SendAsync(i.ToString() + '\t' + new string(charsSets.Select(s => s[random.Next(s.Length)]).ToArray()));
}
source.Complete();
await target.Completion;
}
}
private static async Task<string> GetMessage(string input)
{
int delay = random.Next(25, 6000);
await Task.Delay(delay);
string message = input.ToLowerInvariant() + '\t' + delay.ToString();
MessageGot?.Invoke(null, message);
return message;
}
}
}
默认情况下,StreamWriter
将每4,096字节刷新其缓冲区。您可能希望它在写入的每一行上都刷新。所以代替这个:
var fileAction1 = new ActionBlock<string>(file1.WriteLineAsync);
...执行此操作:
var fileAction1 = new ActionBlock<string>(item =>
{
file1.WriteLine(item);
file1.Flush();
});
使用WriteLineAsync
而不是WriteLine
没有好处,因为尚未使用FileStream
选项打开基础FileOptions.Asynchronous
。