簡體   English   中英

如何在C#中的第一個和第二個方法之后執行第三個方法

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

我通過使用Task類在線程中運行了兩種方法。 我有第三種方法正在主線程中執行。 我希望在第一個和第二個方法之后執行第三個方法。 在下面的代碼中如何做到這一點。 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM