C# TPL数据流块,延迟将消息转发到下一个块
我需要一个数据流块,它根据消息中的时间戳(LogEntry)将消息的转发延迟到下一个块 这是我想到的,但感觉不对。有改进的建议吗C# TPL数据流块,延迟将消息转发到下一个块,c#,.net,task-parallel-library,tpl-dataflow,C#,.net,Task Parallel Library,Tpl Dataflow,我需要一个数据流块,它根据消息中的时间戳(LogEntry)将消息的转发延迟到下一个块 这是我想到的,但感觉不对。有改进的建议吗 private IPropagatorBlock<LogEntry, LogEntry> DelayedForwardBlock() { var buffer = new ConcurrentQueue<LogEntry>(); var source = new BufferBlock<Log
private IPropagatorBlock<LogEntry, LogEntry> DelayedForwardBlock()
{
var buffer = new ConcurrentQueue<LogEntry>();
var source = new BufferBlock<LogEntry>();
var target = new ActionBlock<LogEntry>(item =>
{
buffer.Enqueue(item);
});
Task.Run(() =>
{
LogEntry entry;
while (true)
{
entry = null;
if (buffer.TryPeek(out entry))
{
if (entry.UtcTimestamp < (DateTime.UtcNow - TimeSpan.FromMinutes(5)))
{
buffer.TryDequeue(out entry);
source.Post(entry);
}
}
}
});
target.Completion.ContinueWith(delegate
{
LogEntry entry;
while (buffer.TryDequeue(out entry))
{
source.Post(entry);
}
source.Complete();
});
return DataflowBlock.Encapsulate(target, source);
}
private IPropagatorBlock DelayedForwardBlock()
{
var buffer=新的ConcurrentQueue();
var source=new BufferBlock();
var目标=新操作块(项=>
{
缓冲区。排队(项目);
});
Task.Run(()=>
{
日志输入;
while(true)
{
entry=null;
if(缓冲区TryPeek(出入口))
{
如果(entry.UtcTimestamp<(DateTime.UtcNow-TimeSpan.FromMinutes(5)))
{
buffer.TryDequeue(出入口);
资料来源:员额(条目);
}
}
}
});
目标。完成。与(代表)继续
{
日志输入;
while(buffer.TryDequeue(out entry))
{
资料来源:员额(条目);
}
source.Complete();
});
返回DataflowBlock.enclosure(目标、源);
}
您可以简单地使用一个单线程,通过任务异步等待延迟。延迟
:
IPropagatorBlock<TItem, TItem> DelayedForwardBlock<TItem>(TimeSpan delay)
{
return new TransformBlock<TItem, TItem>(async item =>
{
await Task.Delay(delay);
return item;
});
}
IPropagatorBlock DelayedForwardBlock(时间跨度延迟)
{
返回新的TransformBlock(异步项=>
{
等待任务。延迟(延迟);
退货项目;
});
}
用法:
var block = DelayedForwardBlock<LogEntry>(TimeSpan.FromMinutes(5));
var block=DelayedForwardBlock(TimeSpan.frommins(5));
如果你的代码有效,那么这可能更适合你。非常感谢。有时它可以如此简单:-)