C# 如何在c中执行第一个和第二个方法之后的第三个方法#
我使用C# 如何在c中执行第一个和第二个方法之后的第三个方法#,c#,.net,multithreading,.net-4.0,task-parallel-library,C#,.net,Multithreading,.net 4.0,Task Parallel Library,我使用Taskclass在线程中运行了两个方法。我有第三个方法,它在主线程中执行。我希望在第一个和第二个方法之后执行第三个方法。如何在下面的代码中执行此操作。在Firstmethod()和Secondmethod()之后,仅执行Thirdmethod() static void Main(string[] args) { Task.Factory.StartNew(() => { Firstmethod(); }); Task.Factory.StartNew(()
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);
}
}
static void Main(字符串[]args)
{
Task.Factory.StartNew(()=>{Firstmethod();
});
Task.Factory.StartNew(()=>{Secondmethod();
});
第三种方法();
Console.ReadLine();
}
静态方法()
{
对于(int i=0;i<10;i++)
{
控制台写入线(i);
}
}
静态方法()
{
对于(int i=10;i<20;i++)
{
控制台写入线(i);
}
}
静态空隙第三种方法()
{
对于(int i=20;i<30;i++)
{
控制台写入线(i);
}
}
使用。它在.NET4.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();
}
使用。它在.NET4.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个线程而不是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();
}
虽然Jakub的答案是正确的,但它可能更有效。使用
Task.WaitAll
阻塞线程,同时其他两个线程执行第一个和第二个操作
您可以使用它来执行其中一个方法,而不是阻塞该线程,然后只阻塞另一个方法。这将只使用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();
}
您必须等待第一个和第二个任务。最好使用Task.WaitAllsearch for AutoResetEvent/manualresetevent我使用的是.net 4.0而不是4.5。任何人都可以发布代码来执行此任务。您必须等待第一个和第二个任务。最好使用Task.WaitAllsearch for AutoResetEvent/manualresetevent我使用的是.net 4.0而不是4.5。任何人都可以发布代码来执行此操作吗