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

时间:2015-10-21 13:08:06

标签: c# string winforms listbox backgroundworker

我对编码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;
    }

1 个答案:

答案 0 :(得分:0)

您的代码适合我。 正确的列表框? keepgoing == false? 背景工作者开始了吗?