我需要同时计算文本框中元素的总和和元素的数量。所以我决定创建两个线程——一个用于数字的长度,一个用于元素的总和。但是当我只启动一个线程时 - 它工作正常。但是当我启动第二个线程时 - 表单开始工作缓慢或根本停止工作。我创建了两个线程
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()));
}
}
哪里有问题?同步?
我找到了一个解决方案 - 我Thread.Sleep(1)
在 GetLength 方法中添加了 while 循环