这是代码:
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 将仅添加一次。