前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >.NET 4 System.Threading.Barrier 类

.NET 4 System.Threading.Barrier 类

作者头像
张善友
发布2018-01-22 10:52:02
6070
发布2018-01-22 10:52:02
举报
文章被收录于专栏:张善友的专栏张善友的专栏

Visual Studio 2010 and .NET Framework 4 Training Kit中有个System.Threading.Barrier的Demo,通过Barrier Class我们可以控制线程的运行,做到线程同步的效果。

Barrier Class在使用上十分的简单,只要在Barrier的构造函数中传入participantCount(简单的说就是要等待的线程个数),并在要同步的点调用SignalAndWait方法就可以了。线程会在调用SignalAndWait之后暂停运行,等待所有参与的线程都到达了同步点才继续往下运行。

举个例子来看,假设今天Charlie、Mac、Dennis三个人相约要去西雅图喝咖啡。由于三个人的住的地区不尽相同,且车子都需要加油,因此他们约在途中会经过的加油站待会合后一同前往。这样的情境我们可以通过Thread与Barrier用程序仿真出来。

代码语言:js
复制
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
namespace BarrierDemo 
{ 
    class Program 
    { 
        static Barrier sync; 
        static CancellationToken token; 
        static void Main(string[] args) 
        { 
            var source = new CancellationTokenSource(); 
            token = source.Token; 
            sync = new Barrier(3); 
            var charlie = new Thread(() => DriveToBoston("Charlie", TimeSpan.FromSeconds(1))); charlie.Start(); 
            var mac = new Thread(() => DriveToBoston("Mac", TimeSpan.FromSeconds(2))); mac.Start(); 
            var dennis = new Thread(() => DriveToBoston("Dennis", TimeSpan.FromSeconds(3))); dennis.Start(); 
            //source.Cancel(); 
            charlie.Join(); 
            mac.Join(); 
            dennis.Join(); 
            Console.ReadKey(); 
        } 
        static void DriveToBoston(string name, TimeSpan timeToGasStation) 
        { 
            try 
            { 
                Console.WriteLine("[{0}] Leaving House", name); 
                // Perform some work 
                Thread.Sleep(timeToGasStation); 
                Console.WriteLine("[{0}] Arrived at Gas Station", name); 
                // Need to sync here 
                sync.SignalAndWait(token); 
                // Perform some more work 
                Console.WriteLine("[{0}] Leaving for Boston", name); 
            } 
            catch (OperationCanceledException) 
            { 
                Console.WriteLine("[{0}] Caravan was cancelled! Going home!", name); 
            } 
        } 
    } 
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2009-10-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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