gpt4 book ai didi

c# - 从其他线程更新GUI

转载 作者:行者123 更新时间:2023-12-03 13:20:45 24 4
gpt4 key购买 nike

我正在尝试从另一个线程更新列表框,实现此目的的最简单方法是什么?

我尝试了“调用文本框”,但是没有用。

private void dowork()
{
TcpClient client = new TcpClient();
client.Connect("192.168.1.3", 10);
StreamWriter writer = new StreamWriter(client.GetStream());
StreamReader reader = new StreamReader(client.GetStream());

JObject o = new JObject();
o.Add("comando", 1);
o.Add("dir", @"C:\Users\klein\Desktop\Acionamentos");
writer.Write(o.ToString());
writer.Flush();
JArray array = JArray.Parse(reader.ReadToEnd());
for (int i = 0; i < array.Count; i++)
{
listBox1.Items.Add(array[i]); //update GUI from this thread
}
}

private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(dowork);
t.Start();
}

最佳答案

我将使用BackgroundWorker,可以在DoWork中进行异步操作,使用bgworker.ReportProgress()报告进度,然后将在ProgressChanged中获取回调(我将为处理的每个元素调用ReportProgress),然后就可以更新GUI控件了。

worker 也可以在结束时触发RunWorkerCompleted

YourType arrayitem;

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
TcpClient client = new TcpClient();
client.Connect("192.168.1.3", 10);
StreamWriter writer = new StreamWriter(client.GetStream());
StreamReader reader = new StreamReader(client.GetStream());

JObject o = new JObject();
o.Add("comando", 1);
o.Add("dir", @"C:\Users\klein\Desktop\Acionamentos");
writer.Write(o.ToString());
writer.Flush();
JArray array = JArray.Parse(reader.ReadToEnd());

int percentage;

for (int i = 0; i < array.Count; i++)
{
arrayitem = array[i];
percentage = ((i + 1)*100)/array.Count;
backgroundWorker1.ReportProgress(percentage);
}
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listBox1.Items.Add(arrayitem);
progressBar1.Value = e.ProgressPercentage; // in case you'd want to add a progressbar
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
label1.Text = "Done";
}

请记住,背景工作人员的 WorkerReportProgress属性必须为true。

关于c# - 从其他线程更新GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14542466/

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