テキストボックス内の要素の合計と要素の数を同時に計算する必要があります。そこで、数値の長さ用と要素の合計用の 2 つのスレッドを作成することにしました。しかし、スレッドを 1 つだけ開始すると、正常に動作します。しかし、2 番目のスレッドを開始すると、フォームの動作が遅くなるか、まったく動作しなくなります。2つのスレッドを作成します
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 ループを追加します