首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >.NET 4 System.Threading.CountdownEvent

.NET 4 System.Threading.CountdownEvent

作者头像
张善友
发布2018-01-31 12:37:10
3800
发布2018-01-31 12:37:10
举报
文章被收录于专栏:张善友的专栏张善友的专栏

Visual Studio 2010 and .NET Framework 4 Training Kit中有个System.Threading.CountdownEvent的Demo, CountdownEvent类似于Java中有个 CountDownLatch类, 通过CountdownEvent可以在主线程中线程池中的任务运行,主线程要等待线程池中的任务完成之后才能继续。CountdownEvent Class在使用上十分的简单,只要在CountdownEvent的构造函数中传入信号量的数量。在每个线程启动的地方主线程调用AddCount方法增加信号量计数,线程池中跑的线程调用Signal。然后在主线程中调用Signal和Wait方法,就可以实现主 线程等待X次Signal方法调用之后继续。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
namespace CountdownEventDemo 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            var customers = Enumerable.Range(1, 20); 
            using (var countdown = new CountdownEvent(1)) 
            { 
                foreach (var customer in customers) 
                { 
                    int currentCustomer = customer;                    
                    ThreadPool.QueueUserWorkItem(delegate 
                    { 
                        BuySomeStuff(currentCustomer); 
                        countdown.Signal();                       
                    }); 
                    countdown.AddCount(); 
                } 
                countdown.Signal(); 
                countdown.Wait(); 
            } 
            Console.WriteLine("All Customers finished shopping..."); 
            Console.ReadKey(); 
        } 
        static void BuySomeStuff(int customer) 
        { 
            // Fake work 
            Thread.SpinWait(200000000); 
            Console.WriteLine("Customer {0} finished", customer); 
        } 
    } 
}

相关文章:Fork/Join parallelism with .NET CountdownEvent

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2009-10-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档