I’m trying to update a listbox from another thread, what is the simplest way to achieve this?
I tried Invoking the textbox, but it didn’t work.
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();
}
I would use a
BackgroundWorker, you can do your async stuff inDoWork, report your progress usingbgworker.ReportProgress()and you will get the callback inProgressChanged(I would call ReportProgress for every element processed), then you will be able to update your GUI controls.The worker can also fire
RunWorkerCompletedwhen it ends.Keep in mind your backgroundworker must have true in the
WorkerReportProgressproperty.