0

这是代码:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{
    BackgroundWorker worker = sender as BackgroundWorker; 
    List<string> tempNamesAndTexts = new List<string>();
    string tempDownload = downloadContent();
    GetProfileNames(tempDownload);
    GetTextFromProfile(tempDownload);
    for (int i = 0; i < names.Count; i++)
    {
        tempNamesAndTexts.Add(names[i] + " " + texts[i]);            
    }
    if (InvokeRequired)
    {
        BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(Item + Environment.NewLine))));
    }
    while (true)
    {
        namesAndTexts = new List<string>();
        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
            break;
        }
        else
        {
            string content = downloadContent();
            GetProfileNames(content);
            GetTextFromProfile(content);
            for (int i = 0; i < names.Count; i++)
            {
                 namesAndTexts.Add(names[i] + " " + texts[i]);
            }
            if (InvokeRequired)
            {
                bool result = tempNamesAndTexts.SequenceEqual(namesAndTexts);
                if (result == true)
                {
                }
                else
                {
                    var t = namesAndTexts.Last();

                    if (textBox1.InvokeRequired)
                    {
                        BeginInvoke(new Action(() => textBox1.AppendText(t + Environment.NewLine)), null);
                        return;
                    }
                }
            }
            reader.Close();
            response.Close();
            Thread.Sleep(30000);
        }
    }
}

问题出在这一行:

BeginInvoke(new Action(() => textBox1.AppendText(t + Environment.NewLine)), null);
                                    return;

如果我会放一个reutn; 或打破;它将不断将变量 t 添加到文本框。我希望它只添加一次。并且循环将继续,但变量 t 将仅添加一次。

4

2 回答 2

0

希望我能很好地理解你的问题,听起来你只需要检查一下

if(string.IsNullOrEmpty(textBox1.Text)) //ADD NEW TEXT ONLY IF THERE IS NO ANY
  BeginInvoke(new Action(() => textBox1.AppendText(t + Environment.NewLine)), null);

这自然不用 return了,所以while循环会继续运行。

如果这不是您要的,请澄清。

于 2012-08-12T19:17:39.097 回答
0

如果您希望每次通过循环更新文本,那么您始终可以删除当前字符串的第一行,然后将剩余的内容附加到 (t + Environment.NewLine)。不过,这需要大量的字符串切割。如果你想要一个计数器,你不妨添加一个进度条。

如果这不是你要找的,那么我误解了你的问题。请澄清。

于 2012-08-12T19:34:11.140 回答