1

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

我尝试调用文本框,但它不起作用。

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();
}
4

3 回答 3

1

您可以使用Control.Invoke获取 UI 线程,然后更新列表框。

但是,我建议您考虑使用BackgroundWorker.

于 2013-01-26T23:04:30.260 回答
1

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

工人也可以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。

于 2013-01-26T23:13:03.553 回答
1

您需要使用 Dispatcher.BeginInvoke。您可以查看链接以更好地了解如何从不同线程更新 UI 控件。例如,如果列表框名为 listbox1

for (int i = 0; i < array.Count; i++)
{
    listBox1.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
        new Action(delegate() { listBox1.Items.Add(array[i]) });
}
于 2013-01-28T06:26:52.753 回答