繁体   English   中英

应用程序不等待完成任务

[英]Application is not waiting to finish the Task

我有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中,我仅输出步骤1,步骤3。

正如我所写的那样,代码等待所有线程完成工作。 因此输出应类似于步骤1,步骤3,步骤2

我已经测试过您的代码,并且可以正常工作,问题是从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 ,您将看到预期的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM