I will rephrase the question. This is a simplified code of what i want to do. the Labels will be dynamic and will have to be passed in the function. The function startCount()
will do a lot more and i want to thread out each one to save time. The code works fine (counts and changes the value for now).
I also need to do other functions when all Tasks are done.
I took out the extra Task in the startCount()
function.
As to the other examples, I am not using await
and with the removal ot Task in the startCount()
now the program freezes.
private void Form1_Load(object sender, EventArgs e)
{
strCounter.Add("66"); //Simulate reading file
strCounter.Add("69");
labels = new Label[strCounter.Count]; //Create the Array of Labels
for (int i = 0; i < strCounter.Count; i++)
{
labels[i] = new Label(); //Create label and add it to Form
labels[i].Size = new Size(30, 15);
labels[i].Location = new Point(10, 50 + (i * 20));
labels[i].Text = strCounter[i];
this.Controls.Add(labels[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
List<Task> tasks = new List<Task>(); //Create List of Tasks
for (int i = 0; i < strCounter.Count; i++)
{
int ii = i;
Task LastTask = new Task(() => startCount(i.ToString(), labels[ii]));
tasks.Add(LastTask);
tasks[i].ConfigureAwait(false);
tasks[i].Start();
}
// This line will cause the entire program to freeze.
// If i comment out, the program works fine.
Task.WaitAll(tasks.ToArray());
MessageBox.Show("Should be After");
}
private void startCount(string strCount, Label lbl)
{
for (int i = 0; i < 100; i++)
{
int count = int.Parse(lbl.Text) + 1; //Add 1
writeLabelBox(lbl, count.ToString()); //Use Invoke function
Thread.Sleep(20);
}
}
public void writeLabelBox(Label l, string strA)
{
this.Invoke((MethodInvoker)delegate()
{
l.Text = strA;
});
}