winForm
プロジェクトを進めていますが、listBox1
という名前のlistBox
をフォームに追加しました。 次のようにコードは次のとおりです。タスクが開始することがありますが、時にはそれはなぜですか?それを変更する方法はありますか?
private int inputMax;
private void button1_Click(object sender, EventArgs e)
{
Task t1 = Task.Run(() =>
{
string[] input = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "end" };
inputMax = input.Length;
foreach (string s in input)
{
Thread.Sleep(new Random().Next(1000, 2001));
if (listBox1.InvokeRequired)
{
listBox1.Invoke(new Action(() => listBox1.Items.Add(s)));
}
}
});
Task t2 = Task.Run(() => //t2 sometimes not start
{
while (inputMax > 0)
{
Thread.Sleep(2000);
if (listBox1.InvokeRequired)
{
if ((int)listBox1.Invoke(new Func<int>(() => listBox1.Items.Count)) > 0)
{
listBox1.Invoke(new Action(() => listBox1.Items.RemoveAt(0)));
inputMax--;
}
}
}
});
}
T2、時々起動していないが、なぜですか?変更する方法はありますか?ありがとうございます!
動作環境:問題があり.NET4.5.1
windows10、次の場合にT1とT2、プラスMessageBox.Show( "一部の文字列")の間。プログラムは正常に動作することができます、これはなぜですか?
Task t1 = Task.Run(() =>
{
string[] input = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "end" };
Interlocked.Exchange(ref inputMax, input.Length);
foreach (string s in input)
{
createLog(@"F:\tasklog.txt", "t1---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "---inputMax:"+inputMax.ToString()+ "\r\n");
Thread.Sleep(new Random().Next(1000, 2001));
if(listBox1.InvokeRequired)
{
listBox1.Invoke(new Action(() => listBox1.Items.Add(s)));
}
}
});
MessageBox.Show("some string"); //Add this,the progaram can work properly,why?
Task t2 = Task.Run(() =>
{
while(inputMax>0)
{
createLog(@"F:\tasklog.txt", "t2---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "---inputMax:"+inputMax.ToString()+"\r\n");
Thread.Sleep(2000);
if(listBox1.InvokeRequired)
{
if ((int)listBox1.Invoke(new Func<int>(() => listBox1.Items.Count)) > 0)
{
listBox1.Invoke(new Action(() => listBox1.Items.RemoveAt(0)));
Interlocked.Decrement(ref inputMax);
}
}
}
});
t1とt2の前にinputMaxを計算すると、プログラムは正常に動作します。理由を説明してください?あなたの指導によって、私は多くを学び、私の努力を続けます。どうもありがとうございました! –
@Backbone_Moutain - 't2'は何らかの理由で新しい入力/メッセージを待つことを知らなくてはなりません**。 カウントを渡し、睡眠/待機を使用するのが最も簡単な方法です。 – ironstone13
私は、マルチスレッドサイトについてのより多くの知識をお勧めします。ありがとうございました –