我有一个非常简单的问题。我需要一种方法来轻松地对需要一些时间的消息执行一些处理。在处理过程中,可能会输入新的请求,但除最后一个之外的所有请求都可以被丢弃。TPL Dataflow Broadcastblock丢弃最后一条消息
所以我认为TPL Broadcastblock
应该这样做,例如查看文档和帖子,以及StackExchange。我创建了以下解决方案并为其添加了一些单元测试,但在单元测试中,有时最后一项不会发送。
这不是我所期望的。如果它应该放弃任何东西,我会说它应该放弃第一项,因为如果它不能处理消息它应该覆盖它的缓冲区1。任何人都可以看到它是什么?
任何帮助将不胜感激!
下面是块代码:
/// <summary>
/// This block will take items and perform the specified action on it. Any incoming messages while the action is being performed
/// will be discarded.
/// </summary>
public class DiscardWhileBusyActionBlock<T> : ITargetBlock<T>
{
private readonly BroadcastBlock<T> broadcastBlock;
private readonly ActionBlock<T> actionBlock;
/// <summary>
/// Initializes a new instance of the <see cref="DiscardWhileBusyActionBlock{T}"/> class.
/// Constructs a SyncFilterTarget{TInput}.
/// </summary>
/// <param name="actionToPerform">Thing to do.</param>
public DiscardWhileBusyActionBlock(Action<T> actionToPerform)
{
if (actionToPerform == null)
{
throw new ArgumentNullException(nameof(actionToPerform));
}
this.broadcastBlock = new BroadcastBlock<T>(item => item);
this.actionBlock = new ActionBlock<T>(actionToPerform, new ExecutionDataflowBlockOptions { BoundedCapacity = 1, MaxDegreeOfParallelism = 1 });
this.broadcastBlock.LinkTo(this.actionBlock);
this.broadcastBlock.Completion.ContinueWith(task => this.actionBlock.Complete());
}
public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, bool consumeToAccept)
{
return ((ITargetBlock<T>)this.broadcastBlock).OfferMessage(messageHeader, messageValue, source, consumeToAccept);
}
public void Complete()
{
this.broadcastBlock.Complete();
}
public void Fault(Exception exception)
{
((ITargetBlock<T>)this.broadcastBlock).Fault(exception);
}
public Task Completion => this.actionBlock.Completion;
}
下面是用于测试的代码:
[TestClass]
public class DiscardWhileBusyActionBlockTest
{
[TestMethod]
public void PostToConnectedBuffer_ActionNotBusy_MessageConsumed()
{
var actionPerformer = new ActionPerformer();
var block = new DiscardWhileBusyActionBlock<int>(actionPerformer.Perform);
var buffer = DiscardWhileBusyActionBlockTest.SetupBuffer(block);
buffer.Post(1);
DiscardWhileBusyActionBlockTest.WaitForCompletion(buffer, block);
var expectedMessages = new[] { 1 };
actionPerformer.LastReceivedMessage.Should().BeEquivalentTo(expectedMessages);
}
[TestMethod]
public void PostToConnectedBuffer_ActionBusy_MessagesConsumedWhenActionBecomesAvailable()
{
var actionPerformer = new ActionPerformer();
var block = new DiscardWhileBusyActionBlock<int>(actionPerformer.Perform);
var buffer = DiscardWhileBusyActionBlockTest.SetupBuffer(block);
actionPerformer.SetBusy();
// 1st message will set the actionperformer to busy, 2nd message should be sent when
// it becomes available.
buffer.Post(1);
buffer.Post(2);
actionPerformer.SetAvailable();
DiscardWhileBusyActionBlockTest.WaitForCompletion(buffer, block);
var expectedMessages = new[] { 1, 2 };
actionPerformer.LastReceivedMessage.Should().BeEquivalentTo(expectedMessages);
}
[TestMethod]
public void PostToConnectedBuffer_ActionBusy_DiscardMessagesInBetweenAndProcessOnlyLastMessage()
{
var actionPerformer = new ActionPerformer();
var block = new DiscardWhileBusyActionBlock<int>(actionPerformer.Perform);
var buffer = DiscardWhileBusyActionBlockTest.SetupBuffer(block);
actionPerformer.SetBusy();
buffer.Post(1);
buffer.Post(2);
buffer.Post(3);
buffer.Post(4);
buffer.Post(5);
actionPerformer.SetAvailable();
DiscardWhileBusyActionBlockTest.WaitForCompletion(buffer, block);
var expectedMessages = new[] { 1, 5 };
actionPerformer.LastReceivedMessage.Should().BeEquivalentTo(expectedMessages);
}
private static void WaitForCompletion(IDataflowBlock source, IDataflowBlock target)
{
source.Complete();
target.Completion.Wait(TimeSpan.FromSeconds(1));
}
private static BufferBlock<int> SetupBuffer(ITargetBlock<int> block)
{
var buffer = new BufferBlock<int>();
buffer.LinkTo(block);
buffer.Completion.ContinueWith(task => block.Complete());
return buffer;
}
private class ActionPerformer
{
private readonly ManualResetEvent resetEvent = new ManualResetEvent(true);
public List<int> LastReceivedMessage { get; } = new List<int>();
public void Perform(int message)
{
this.resetEvent.WaitOne(TimeSpan.FromSeconds(3));
this.LastReceivedMessage.Add(message);
}
public void SetBusy()
{
this.resetEvent.Reset();
}
public void SetAvailable()
{
this.resetEvent.Set();
}
}
}
感谢您的回复(以及附注;) 因此,如果我正确理解您,广播区块在覆盖它的缓冲区时正在做它的工作,但Actionblock实际上是在放弃它们?有趣! 虽然在检查Post的返回值时我不理解您的其他评论。我不会将消息发布到动作块,它是通过OfferMessage方法完成的。Bufferblock不会工作,因为它会缓存所有传入的消息,而我希望只有一个缓冲区每次在接收器繁忙时收到消息时被覆盖。你能否澄清这件事? –
已更新的答案。 – VMAtm
好的,谢谢你的解释。所以我得出结论,我不能使用内置的TPL逻辑来实现它,并且必须找到我自己的解决方案。再次感谢! –