亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何并行延遲多個消息?

如何并行延遲多個消息?

C#
江戶川亂折騰 2021-05-01 16:13:57
我正在做一些TCP編程,并且我想模擬一些延遲。每個“消息”(代表序列化對象的byte [])必須延遲一段時間t。我以為我可以使用一種功能來收集原始消息:private Queue<byte[]> rawMessages = new Queue<byte[]>();private void OnDataReceived(object sender, byte[] data){    rawMessages.Enqueue(data);}帶有while循環的另一種方法,該方法可以連續讀取rawMessages并延遲每個循環:private Queue<byte[]> delayedRawMessages = new Queue<byte[]>();delayMessagesInTask = Task.Factory.StartNew(() =>{    while (true) //TODO: Swap a cancellation token    {        if(rawMessages.Count > 0){            var rawMessage = rawMessages.Dequeue();            //???            //Once the message has been delayed, enqueue it into another buffer.            delayedRawMessages.Enqueue(rawMessage);        }    }});我以為要延遲每條消息,我可以有另一種方法來生成線程,該線程Thread.Sleep(t)用于等待時間t然后排隊delayedRawMessages。我敢肯定這會奏效,但我認為必須有更好的方法。該Thread.Sleep方法的問題在于,消息2可能會在消息1之前完成延遲……我顯然需要將消息延遲并以正確的順序執行,否則我將不會使用TCP。我正在尋找一種方法來做到這一點,該方法將t盡可能長時間地延遲,并且不會通過降低速度來影響應用程序的其余部分。這里有人知道更好的方法嗎?
查看完整描述

1 回答

?
慕運維8079593

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。


我真的不知道這是否是實現我的目標的理想方法,但目前仍有效。


查看完整回答
反對 回復 2021-05-16
  • 1 回答
  • 0 關注
  • 195 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號