gpt4 book ai didi

c# - 使用两个线程写入textBox

转载 作者:行者123 更新时间:2023-12-03 12:51:02 27 4
gpt4 key购买 nike

我有一些 Unresolved 线程问题。这是我第一次做。我知道如何使用一个线程在textBox中进行编写,但是我不知道如何使用其中的两个线程来完成这项工作。任何人都有线索,我要做什么才能能够使用两个线程写入同一textBox,但不能同时写入。谢谢你。

最佳答案

这是一个使用两个线程将随机数写入多行文本框的示例。正如Brandon和Jon B指出的那样,您需要使用Invoke()来序列化对GUI线程的调用。

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Random m_random = new Random((int)DateTime.Now.Ticks);
ManualResetEvent m_stopThreadsEvent = new ManualResetEvent(false);

private void buttonStart_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(new ThreadStart(ThreadOne));
Thread t2 = new Thread(new ThreadStart(ThreadTwo));

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

private void ThreadOne()
{
for(;;)
{
int n = m_random.Next(1000);
AppendText(String.Format("One: {0}\r\n", n));
if(m_stopThreadsEvent.WaitOne(n))
{
break;
}
}
}

private void ThreadTwo()
{
for(;;)
{
int n = m_random.Next(1000);
AppendText(String.Format("Two: {0}\r\n", n));
if(m_stopThreadsEvent.WaitOne(n))
{
break;
}
}
}

delegate void AppendTextDelegate(string text);

private void AppendText(string text)
{
if(textBoxLog.InvokeRequired)
{
textBoxLog.Invoke(new AppendTextDelegate(this.AppendText), new object[] { text });
}
else
{
textBoxLog.Text = textBoxLog.Text += text;
}
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
m_stopThreadsEvent.Set();
}
}

关于c# - 使用两个线程写入textBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/812595/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com