peter
peter

Reputation: 8662

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

Upvotes: 1

Views: 213

Answers (2)

i3arnon
i3arnon

Reputation: 116548

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

Upvotes: 1

Jakub Lortz
Jakub Lortz

Reputation: 14896

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

Upvotes: 4

Related Questions