简体   繁体   English

在 C# 中以预设的时间表运行四个任务

[英]Run four tasks with a preset schedule in C#

I have an exercise in asynchronous programming like this: There are 4 Tasks: Task1 , Task2 , Task3 , Task4 .我有一个这样的异步编程练习:有 4 个任务: Task1Task2Task3Task4 Task1 and Task2 run in parallel. Task1Task2并行运行。 Task3 is only run when either Task1 or Task2 completes. Task3仅在Task1Task2完成时运行。 Task4 runs when all 3 previous tasks must be completed. Task4在必须完成所有 3 个先前任务时运行。 This is how I do it, but my teacher asked me not to separate the function to handle Task.WaitAny() (in the picture is the waitAny() function), and not to use async in ContinueWith .我是这样做的,但是我的老师要求我不要分开处理Task.WaitAny()的函数(图中是waitAny()函数),不要在ContinueWith中使用 async 。 Can someone help me?有人能帮我吗?
Screenshot with code .带有代码的屏幕截图

static async Task<int> waitAny()
{
    return Task.WaitAny(runTask1(), runTask2());
}

static void Main(string[] args)
{
    waitAny().ContinueWith( 
    async (_taskToContinue) => 
    {
        await runTask3();

        Task.WaitAll(runTask1(), runTask2(), runTask3());

        await runTask4();

    });

    Console.ReadKey();
}

Would do it like this then.那时会这样做。

    static void Main(string[] args)
    {
        var task1 = runTask1();
        var task2 = runTask2();

        Task.WhenAny(task1, task2).ContinueWith(task =>
        {
            var task3 = runTask3();

            Task.WaitAll(task1, task2, task3);

            var task4 = runTask4();
            task4.Wait();
        });
    }

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

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