class Program
{
static CountdownEvent _count = new CountdownEvent(3);
static void Main(string[] args)
{
Task.Factory.StartNew(() =>
{
Thread.Sleep(2000);
Console.WriteLine("thread 1 complete");
_count.Signal();
});
Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
Console.WriteLine("thread 2 complete");
_count.Signal();
});
Task.Factory.StartNew(() =>
{
Thread.Sleep(3000);
Console.WriteLine("thread 3 complete");
_count.Signal();
});
Console.WriteLine("waiting tasks....");
_count.Wait();
Console.WriteLine("all task completed");
Console.ReadKey();
}
}
使用TASK的waitAll可以达到同样的效果:
var t1 = Task.Factory.StartNew(() =>
{
Thread.Sleep(2000);
Console.WriteLine("thread 1 complete");
});
var t2 = Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
Console.WriteLine("thread 2 complete");
});
var t3 = Task.Factory.StartNew(() =>
{
Thread.Sleep(3000);
Console.WriteLine("thread 3 complete");
});
Console.WriteLine("waiting tasks....");
Task.WaitAll(t1, t2, t3);
Console.WriteLine("all task completed");
Console.ReadKey();
c# 中CountDownEvent的使用
最新推荐文章于 2023-12-13 14:11:13 发布
本文介绍如何使用 C# 的 Task 类实现并发任务的等待和同步,通过 StartNew 方法创建多个任务,利用 Wait 或 WaitAll 方法确保所有任务完成后再执行后续操作。
448

被折叠的 条评论
为什么被折叠?



