[英]How to set CPU priority for multiple ActionBlocks running at the same time?
我有一堆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
選項打開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.