[英]how to execute a third method after first and second method in c#
I have two methods running in threads by using Task
class. 我通过使用
Task
类在线程中运行了两种方法。 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 后
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);
}
}
Use Task.WaitAll
. 使用
Task.WaitAll
。 It's available in .NET 4.0. 在.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. 尽管雅库布(Jakub)的答案是正确的,但它可能更有效。 Using
Task.WaitAll
blocks the thread while 2 other threads perform the first and second operations. 使用
Task.WaitAll
阻止线程,而其他2个线程执行第一个和第二个操作。
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:
这将仅使用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.