C# 如何并行延迟多条消息?

C# 如何并行延迟多条消息?,c#,multithreading,task,C#,Multithreading,Task,我正在做一些TCP编程,我想模拟一些延迟 表示序列化对象的字节[]的每条消息必须延迟一段时间t。我想我可以有一个函数来收集原始消息: private Queue<byte[]> rawMessages = new Queue<byte[]>(); private void OnDataReceived(object sender, byte[] data) { rawMessages.Enqueue(data); } 我认为要延迟每条消息,我可以使用另一种方法生

我正在做一些TCP编程,我想模拟一些延迟

表示序列化对象的字节[]的每条消息必须延迟一段时间t。我想我可以有一个函数来收集原始消息:

private Queue<byte[]> rawMessages = new Queue<byte[]>();
private void OnDataReceived(object sender, byte[] data)
{
    rawMessages.Enqueue(data);
}
我认为要延迟每条消息,我可以使用另一种方法生成一个线程,该线程使用thread.Sleept等待时间t,然后将delayedRawMessages排队。我相信这会奏效,但我认为一定有更好的办法。使用Thread.Sleep方法的问题是,消息2可能在消息1之前完成延迟。。。我显然需要消息被延迟,并以正确的顺序执行,否则我将不会使用TCP

我正在寻找一种方法来做到这一点,它将延迟尽可能接近时间t,并且不会通过减慢速度而影响应用程序的其余部分


这里有人知道更好的方法吗?

我决定采用生产者/多消费者的方法

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);
        }
    }
}
要使用它,请创建一个新的LatencySimulator,设置其“类型”、要模拟的最大使用者和延迟。调用CreateConsmers,然后填充inputQueue。消息延迟后,它们将出现在DelayedMessageQueue中

我真的不知道这是否是实现我目标的理想方式,但它是有效的。。。现在

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);
        }
    }
}