Ich arbeite ein winForm
Projekt, fügte ich eine listBox
in Form, als listBox1
benannt. Der Code ist wie folgt:Task manchmal starten, manchmal nicht, warum? Wie man es ändert?
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, beginnt manchmal nicht, warum? wie man ändert? Danke!
Betriebsumgebung: Microsoft Windows 10, .NET4.5.1
Es gibt ein Problem: wenn zwischen T1 und T2 sowie einem MessageBox.Show ("some string"); das Programm kann auch richtig funktionieren, ist das der Grund?
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);
}
}
}
});
Berechnen Sie inputMax vor t1 und t2, das Programm kann ordnungsgemäß funktionieren. Würdest du bitte erklären warum? Durch Ihre Anleitung habe ich viel gelernt und werde meine Bemühungen fortsetzen. vielen Dank! –
@Backbone_Moutain - weil 't2' irgendwie wissen muss ** wann man keine neuen Eingaben/Nachrichten erwartet **. Das Übergeben einer Zählung und das Verwenden von Schlafen/Warten ist der einfachste Weg, dies zu tun. – ironstone13
Ich verstehe, bitte empfehlen Sie mehr Wissen über Multithreading-Sites. Danke –