c# - 如何在第一个和第二个方法之后执行第三个方法

how to execute a third method after first and second method in c#

我在线程中使用 Task class 有两个方法 运行。我有第三种方法在主线程中执行。我希望在第一种和第二种方法之后执行第三种方法。如何在以下代码中执行此操作。在Firstmethod()Secondmethod()之后只有Thirdmethod()被执行

static void Main(string[] args)
{
    Task.Factory.StartNew(() => { Firstmethod();
    });
    Task.Factory.StartNew(() => { Secondmethod();
    });

        Thirdmethod();
    Console.ReadLine();
}

static void Firstmethod()
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
    }
}
static void Secondmethod()
{
    for (int i = 10; i < 20; i++)
    {
        Console.WriteLine(i);
    }
}
static void Thirdmethod()
{
    for (int i = 20; i < 30; i++)
    {
        Console.WriteLine(i);
    }
}

使用Task.WaitAll。它在 .NET 4.0 中可用。

static void Main(string[] args)
{
    Task t1 = Task.Factory.StartNew(() => {
        Firstmethod();
    });
    Task t2 = Task.Factory.StartNew(() => {
        Secondmethod();
    });

    Task.WaitAll(t1, t2);
    Thirdmethod();
    Console.ReadLine();
}

虽然 Jakub 的回答是正确的,但它可能会更有效率。使用 Task.WaitAll 阻塞线程,而其他 2 个线程执行第一个和第二个操作。

您可以使用它来执行其中一种方法,然后才阻塞另一个方法,而不是阻塞该线程。这将只使用 2 个线程而不是 3 个线程,甚至可能根本不会阻塞:

static void Main()
{
    Task task = Task.Factory.StartNew(() => FirstMethod()); // use another thread
    SecondMethod(); // use the current thread
    task.Wait(); // make sure the first method completed
    Thirdmethod();
}