Thanks to both of you for your valuable help. Changed it as shown below and got it working without loosing sequence and with corresponding thread id...
private void TaskRunButton_Click(object sender, EventArgs e)
{
// clear the list before writing
listBox.Items.Clear();
Task demoTask = new Task(DemoTask);
demoTask.Start();
}
private void DemoTask()
{
try
{
List<Task> tsk1 = new List<Task>();
List<Task> tsk2 = new List<Task>();
for (int i = 0; i < 10; i++)
{
tsk1.Add(new Task(TaskDemoWait100ms));
tsk2.Add(new Task(TaskDemoWaitWait200ms));
}
for (int i = 0; i < 10; i++)
{
tsk1\[i\].Start();
tsk2\[i\].Start();
tsk2\[i\].Wait();
listBox.BeginInvoke(new separatorDelegate(() =>
{ listBox.Items.Add("------------"); }));
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
delegate void taskdelegate(int threadId);
delegate void separatorDelegate();
private void TaskDemoWait100ms()
{
Thread.Sleep(100);
object[] param = new object[1];
param\[0\] = (object)Thread.CurrentThread.ManagedThreadId;
listBox.BeginInvoke(new taskdelegate((int threadId) =>
{ listBox.Items.Add("Wait 100 ms, Thread Id = " + threadId); }), param);
}
private void TaskDemoWaitWait200ms()
{
Thread.Sleep(200);
object[] param = new object[1];
param\[0\] = (object)Thread.CurrentThread.ManagedThreadId;
listBox.BeginInvoke(new taskdelegate((int threadId) =>
{ listBox.Items.Add("Wait 200 ms, Thread Id = " + threadId); }), param);
}