【问题标题】:Application is not waiting to finish the Task应用程序没有等待完成任务
【发布时间】:2016-01-01 01:42:49
【问题描述】:

我有 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

【问题讨论】:

  • 在 LINQPad 中运行它,我无法重现您的问题。我得到了预期的输出。
  • 我同意,情况2似乎没有问题。只需等待几秒钟,Step2就会完成。只有在Step2 之后Task.WaitAll 按计划完成。

标签: c# task continuations


【解决方案1】:

我已经测试了你的代码,它工作得很好,问题是从 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,您将看到预期的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2013-12-18
    相关资源
    最近更新 更多