Omer K Omer K - 2 months ago 7
C# Question

Task doesn't run in parallel

I have a task, but processes inside it don't run in parallel. Second one waits for the first one to compelete. Can you explain why and how can I correct this? I want both of them run at the same time.

And second question, Should I use task instead of threads?

Thanks in advance.

new Task(() =>
{
Counter1();
Counter2();
}).Start();




private void Counter2()
{
for (int i = 0; i < 30; i++)
{
Thread.Sleep(500);
label2.Text = i.ToString();
}
}

private void Counter1()
{
for (int i = 0; i < 30; i++)
{
Thread.Sleep(500);
label3.Text = i.ToString();
if(i == 15)
Thread.Sleep(3000);
}
}

Answer

Parent Task - Child Task can bu used

new Task(() =>
{
     Task.Factory.StartNew(Counter1);
     Task.Factory.StartNew(Counter2);
}).Start();

private void Counter2()
{
    for (int i = 0; i < 30; i++)
    {
        Thread.Sleep(500);
        label2.Text = i.ToString();
    }
}

private void Counter1()
{
    for (int i = 0; i < 30; i++)
    {
        Thread.Sleep(500);
        label3.Text = i.ToString();
        if(i == 15)
            Thread.Sleep(3000);
    }
}e
Comments