Hi I'm new to multithreading and TPL - testing Task call and writing the status back to text box on Main UI and didn't get the expected result. I'm testing this feature because I need to implement the tool for my work. My program will loop to create 30 tasks and start and showing which task are processing in Text box. I pass "i" counter into DoWork fuction and display that "i" counter. My Code as below
private void DoWork(object state)
{
object[] obj = state as object[];
int i = Convert.ToInt32(obj[0]);
Invoke(new MethodInvoker(delegate()
{
richTextBox1.Text += "Testing" + i.ToString() + "\n";
}));
}
private void btnTest_Click(object sender, EventArgs e)
{
for (int i = 0; i < 30; i++)
{
Task t1 = new Task(() => DoWork(new object[] {i}) );
t1.Start();
}
}
I'm expecting 1 to 30 display in text box in random order but it display like this. I have attached the image as well as display in here. enter image description here
the result seems odd and mostly displaying like below (almost all display 30). "i" is parameter passing to "DoWork" as object.
Testing0 Testing3 Testing12 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30 Testing30
Your help to make me understand and figure out to fix this issue is greatly appreciated.
Regards William