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



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

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

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 = "";
}
}

左:发送右:接收

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

发送进程必须休眠3秒钟。

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

如何解决这个问题?

您可以使用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
}
}

最新更新