应用程序不等待完成任务

时间:2015-10-04 07:19:09

标签: c# task continuations

我有3个方法名称(step1,step2,step3),其中一个有强化计算。 我有 Step1和Step2彼此独立的情况,Step3只能在Step1之后运行

这是我的代码

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

在案例2中,我只获得输出Step1,Step 3.

我在哪里写代码等待所有线程完成他们的工作。所以输出应该像这样 step1,step 3,step 2

1 个答案:

答案 0 :(得分:0)

我已经测试了您的代码,它运行得很好,问题是 从1迭代到Int32.MaxValue需要很长时间 (周围在我的电脑上15秒),在以下代码中:

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

Int32.MaxValue更改为3000000 ,您将看到预期的结果。