Omer
Omer

Reputation: 10264

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);
        }
    }

Upvotes: 1

Views: 374

Answers (1)

Barb C. Goldstein
Barb C. Goldstein

Reputation: 454

Use Parallel.Invoke and call Counter1() and Counter2() as shown in following example from MSDN (after updating the () anonymous lambda invocation to invoke your 2 methods.

        #region ParallelTasks
        // Perform three tasks in parallel on the source array
        Parallel.Invoke(() =>
                         {
                             Console.WriteLine("Begin first task...");
                             GetLongestWord(words);
                         },  // close first Action

                         () =>
                         {
                             Console.WriteLine("Begin second task...");
                             GetMostCommonWords(words);
                         }, //close second Action

                         () =>
                         {
                             Console.WriteLine("Begin third task...");
                             GetCountForWord(words, "species");
                         } //close third Action
                     ); //close parallel.invoke

        Console.WriteLine("Returned from Parallel.Invoke");
        #endregion

Upvotes: 3

Related Questions