1 回答

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 關注
- 195 瀏覽
添加回答
舉報