从后台工作者向列表框添加字符串(调用)

Adding Strings to listbox from a background worker (invoking)

我对 c# 编码还很陌生,我正在尝试使用后台工作程序(以避免停止我的 GUI)来 运行 一个 ping 循环,其结果将打印到我的列表框中gui 每次 ping 就像一个标准的 cmd 提示符。

我的代码可以编译,但文本没有出现在列表框中,如果能帮助我找出哪里出错了,那就太好了。

谢谢

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int secs = DateTime.Now.Second;
        while (keepgoing == true)
        {
            if (secs != DateTime.Now.Second)
            {
                secs = DateTime.Now.Second;
                using (Ping p = new Ping())
                {
                    int hh = DateTime.Now.Hour;
                    int mm = DateTime.Now.Minute;
                    int ss = DateTime.Now.Second;

                    string time = "";

                    if (hh < 10)
                    {
                        time += "0";
                        time += hh;
                    }
                    else
                    {
                        time += hh;
                    }
                    time += ":";

                    if (mm < 10)
                    {
                        time += "0";
                        time += mm;
                    }
                    else
                    {
                        time += mm;
                    }
                    time += ":";

                    if (ss < 10)
                    {
                        time += "0";
                        time += ss;
                    }
                    else
                    {
                        time += ss;
                    }
                    string successString = ("Ping Successful - " +       p.Send(textBox2.Text).RoundtripTime.ToString() + "ms    " + time + "\n");
                    Invoke((Action<string>)AddItemBox2,successString);
                }
            }
        }
        listBox2.Items.Add("\n");
    }

    private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    private void AddItemBox2(string print)
    {
        listBox2.Items.Add(print);
        listBox2.Refresh();
        listBox2.TopIndex = listBox2.Items.Count - 1;
    }

你的代码对我有用。 正确的列表框? 继续==假? 后台工作人员开始了吗?