Search code examples
c#taskcontinuations

Application is not waiting to finish the Task


I have 3 methods names (step1, step2,step3) ,and one of those have Intensive calculation. I have situation like Step1 and Step2 are independent of each other, and Step3 can be run only after Step1

This is my code

static void Main(string[] args)
{
    Console.WriteLine("Step1, Step2and Step3are independent of each other.\n");

    Console.WriteLine("Step1 and Step2 are independent of each other, and Step3 can be run only after Step1\n \n");
    Console.WriteLine("Step1 and Step2 are independent of each other, and Step3 can be run only after Step1 and Step2 finish.\n \n");
    Console.WriteLine(" Step1 and Step2 are independent of each other, and Step3 can be run only after Step1 or Step2 finishes.\n \n");

    var getCase = Int32.Parse(Console.ReadLine());
    switch (getCase)
    {
        case 1:
            Parallel.Invoke(Step1, Step2, Step3);
            break;
        case 2:
            Task taskStep1 = Task.Run(() => Step1());
            Task taskStep2 = Task.Run(() => Step2());
            Task taskStep3 = taskStep1.ContinueWith((previousTask) => Step3());
            Task.WaitAll(taskStep2, taskStep3);
            break;
        case 3:
            Task step1Task = Task.Run(() => Step1());
            Task step2Task = Task.Run(() => Step2());
            Task step3Task = Task.Factory.ContinueWhenAll(
            new Task[] { step1Task, step2Task },
            (previousTasks) => Step3());
            step3Task.Wait();
            break;
        case 4:
            Task TaskStep1 = Task.Run(() => Step1());
            Task Taskstep2 = Task.Run(() => Step2());
            Task Taskstep3 = Task.Factory.ContinueWhenAny(
            new Task[] { TaskStep1, Taskstep2 },
            (previousTask) => Step3());
            Taskstep3.Wait();
            break;
    }


    Console.ReadLine();
}


static void Step1()
{
    Console.WriteLine("Step1");
}
static void Step2()
{
    double result = 10000000d;
    var maxValue = Int32.MaxValue;
    for (int i = 1; i < maxValue; i++)
    {
        result /= i;
    }
    Console.WriteLine("Step2");
}
static void Step3()
{
    Console.WriteLine("Step3");
}

In case 2, I'm getting output only Step1 , Step 3.

Where as I have written code to wait all thread to finish their work. so output should be like this step1, step 3, step 2


Solution

  • I've tested your code and it works just fine, the problem is that iterating from 1 to Int32.MaxValue takes a long time (around 15 seconds on my computer), in this following code:

    static void Step2()
    {
        double result = 10000000d;
        var maxValue = Int32.MaxValue;
        for (int i = 1; i < maxValue; i++)
        {
            result /= i;
        }
        Console.WriteLine("Step2");
    }
    

    Change Int32.MaxValue to 3000000 and you will see your expected result.