我需要同時計算文本框中元素的總數和元素的數量。所以我決定創建兩個線程 - 一個用於數字的長度,另一個用於元素的總和。但是當我只啓動一個線程時 - 它的工作是正確的。但是當我開始第二個線程 - 表單開始工作緩慢或停止工作。 創建兩個線程在winforms中遇到麻煩
thrd = new Thread(GetLength);
thrd.Start();
thrd1 = new Thread(SetSum);
thrd1.Start();
而這些線程的功能在文本框的數目的計算長度和它的元件的運算量。
private void SetSum()
{
while (true)
{
if (this.label3.InvokeRequired)
this.Invoke(new Action(() => label3.Text = this.GetSum().ToString()));
}
}
private int GetSum()
{
string n = textBox1.Text;
int sum = 0;
for (int i = 0; i < n.Length; i++)
{
try
{
sum += int.Parse(n[i].ToString());
}
catch (FormatException) { };
}
return sum;
}
private void GetLength()
{
while (true)
{
if (this.label2.InvokeRequired)
this.Invoke(new Action(() => label2.Text = " | Length = " + textBox1.Text.Length.ToString()));
}
}
問題在哪裏?同步?
我已經找到了解決辦法 - 我在while循環對GetLength方法
但除了線程無限循環沒有其他解決方案。或者它不會移動到任何其他形式的操作。 – lapots
是的,沒有線程。如果目標是在TextBox的內容發生更改時更新標籤,則只需TextChanged事件即可。在這種情況下,您的線程方法有太多錯誤需要修復。 –
TextChanged的解決方案有效! – lapots