如何在高速线程之间逐线程同步数据?

时间:2021-07-02 14:10:09

标签: c# .net multithreading winforms

数据通信过程中出现错误,所以我问你一个类似的例子。

以下示例由发送线程和接收线程组成:

 private void Form1_Load(object sender, EventArgs e)
    {
        t1 = new Thread(() => SendProc());
        t2 = new Thread(() => ReceiveProc());

        t1.Start();
        t2.Start();
    }


    private void SendProc()
    {
        while (true)
        {
            buf = val.ToString();
            ++val;

            this.Invoke(new Action(delegate ()
            {
                this.richTextBox1.Text = val.ToString() + "\n" + this.richTextBox1.Text;
                textBox1.Text = (++cnt1).ToString();
            }));

            Thread.Sleep(SEND_TIME_INTERVAL);
        }

    }



    private void ReceiveProc()
    {

        while (true)
        {
            if (string.IsNullOrEmpty(buf))
            {
                Thread.Sleep(RECEIVE_TIME_INTERVAL);
                continue;
            }

            this.Invoke(new Action(delegate ()
            {
                this.richTextBox2.Text = val.ToString() + "\n" + this.richTextBox2.Text;
                textBox2.Text = (++cnt2).ToString();
            }));

            buf = "";
        }
    }

Left : Send Right : Receive

奇怪的是,发送数据和接收数据不同步。

发送过程必须休眠 3 秒。

示例源代码: https://drive.google.com/file/d/1bqTyWdLViWw-glFztzYVoLah1egcZU7g/view?usp=sharing

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以使用BlockingCollection

var _items = new BlockingCollection<string>(10); // 10 is max buffered items
void SendProc() {
    for (int i = 0; i < 10000; i++) {
        _items.Add(i.ToString()); // blocks if more than 10 items not consumed
        Thread.Sleep(SEND_TIME_INTERVAL);
    }
    _items.CompleteAdding();
}
void ReceiveProc() {
    while (!_items.IsCompleted) {
        var item = _items.Take(); // blocks if _items empty
        // this.Invoke(...); // use item
    }
}