zoukankan      html  css  js  c++  java
  • .NET 4 System.Threading.CountdownEvent

    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

    欢迎大家扫描下面二维码成为我的客户,为你服务和上云

  • 相关阅读:
    27. 为什么线程执行要调用start而不是直接run
    25. ThreadLocal的使用场景
    23. 线程如何退出结束
    20. Java字符串格式化方法
    21. 时间的格式化方法
    19. 用过spring的线程池还是java的线程池?
    17. zookeeper的实现机制,有缓存,如何存储注册服务的
    面试-spring 那些事
    Apache服务器和tomcat服务器有什么区别?
    JNDI 和JDBC的区别
  • 原文地址:https://www.cnblogs.com/shanyou/p/1590890.html
Copyright © 2011-2022 走看看