這是代碼:我如何使添加到textBox的文本只添加一次,而不是所有時間都在循環中?
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將只添加一次。
Tigran no我不想檢查textBox1.Text是否爲空或空。當IF條件爲false時,我只想添加一次字符串變量t。如果你看到的話,那裏有bool,如果它真的如果它真的會進入,它將不會執行任何操作,並且會將變量T添加到textBox1中。問題是這個t變量在while(true)循環中,一旦它被添加到textBox中,出於某種原因,它將會停留在那裏,循環將繼續向textBox添加變量t,而不是在文本框中查看例如stringt:「大家好」一次,我會看到它添加不間斷。 – user1593871 2012-08-12 22:59:49
我需要以某種方式將t添加到文本框當布爾如果錯誤但只有一次!並保持循環繼續。在這種情況下,因爲它現在被卡在這個t變量行中並且不斷添加t變量不間斷的時間到textBox。 – user1593871 2012-08-12 23:00:50
修正了它。將盡快在問題中發佈我的解決方案。謝謝你們。 – user1593871 2012-08-13 00:47:08