简体   繁体   中英

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

I have two methods running in threads by using Task class. I have a third method which is executing in main thread. I want third method to be executed after first and second method. How to do this in following code. After Firstmethod() and Secondmethod() only Thirdmethod() to be executed

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);
    }
}

Use Task.WaitAll . It's available in .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();
}

While Jakub's answer is correct, it could be more efficient. Using Task.WaitAll blocks the thread while 2 other threads perform the first and second operations.

Instead of blocking that thread you can use it to execute one of the methods, and only then block on the other one. This will only use 2 threads instead of 3 and may even not block at all:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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