1 回答
![?](http://img1.sycdn.imooc.com/533e4bd900011a1d02000200-100-100.jpg)
TA贡献1876条经验 获得超5个赞
我决定采用生产者/多个消费者的方法。
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class LatencySimulator {
public enum SimulatorType { UP, DOWN };
public SimulatorType type;
public int latency = 0;
public int maxConsumers = 50;
public BlockingCollection<byte[]> inputQueue = new BlockingCollection<byte[]>(new ConcurrentQueue<byte[]>());
public Queue<byte[]> delayedMessagesQueue = new Queue<byte[]>();
void CreateConsumers()
{
for (int i = 0; i < maxConsumers; i++)
{
Task.Factory.StartNew(() => Consumer(),TaskCreationOptions.LongRunning);
}
}
private void Consumer()
{
foreach (var item in inputQueue.GetConsumingEnumerable())
{
Thread.Sleep(latency);
delayedMessagesQueue.Enqueue(item);
}
}
}
要使用它,请创建一个new LatencySimulator,设置其“类型”,最大使用者和要模拟的等待时间。致电CreateConsmers(),然后填充inputQueue。邮件被延迟后,它们将出现在中delayedMessagesQueue。
我真的不知道这是否是实现我的目标的理想方法,但目前仍有效。
- 1 回答
- 0 关注
- 179 浏览
添加回答
举报