Welcome

首页 / 软件开发 / .NET编程技术 / Windows 8 Store Apps学习(47) 多线程之线程同步: Semaphore等

Windows 8 Store Apps学习(47) 多线程之线程同步: Semaphore等2013-12-10 cnblogs webabcd多线程之线程同步: Semaphore, CountdownEvent, Barrier, ManualResetEvent, AutoResetEvent

介绍

重新想象 Windows 8 Store Apps 之 线程同步

Semaphore - 信号量

CountdownEvent - 通过信号数量实现线程同步

Barrier - 屏障

ManualResetEvent - 手动红绿灯

AutoResetEvent - 自动红绿灯

示例

1、演示 Semaphore 的使用

Thread/Lock/SemaphoreDemo.xaml

<Pagex:Class="XamlDemo.Thread.Lock.SemaphoreDemo"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="using:XamlDemo.Thread.Lock"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"><Grid Background="Transparent"><StackPanel Margin="120 0 0 0"><TextBlock Name="lblMsg" FontSize="14.667" /></StackPanel></Grid></Page>
Thread/Lock/SemaphoreDemo.xaml.cs

/* * 演示 Semaphore 的使用 ** Semaphore - 信号量 * SemaphoreSlim - 轻量级的 Semaphore ** 注: * 直译 Semaphore 的话不太好理解,可以将 Semaphore 理解为一个许可证中心,该许可证中心的许可证数量是有限的 * 线程想要执行就要先从许可证中心获取一个许可证(如果许可证中心的许可证已经发完了,那就等着,等着其它线程归还许可证),执行完了再还回去 */using System;using System.Collections.Generic;using System.Threading;using System.Threading.Tasks;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Navigation;namespace XamlDemo.Thread.Lock{public sealed partial class SemaphoreDemo : Page{/* * Semaphore(int initialCount, int maximumCount, string name) * initialCount - 许可证中心初始拥有的许可证数量,即初始情况下已经发出的许可证数量为maximumCount - initialCount * maximumCount - 许可证中心总共拥有的许可证数量 * name - 许可证中心的名称 * Semaphore OpenExisting(string name) - 打开指定名称的许可证中心 */// 实例化一个许可证中心,该中心拥有的许可证数量为 2 个private Semaphore _semaphore = new Semaphore(2, 2);public SemaphoreDemo(){this.InitializeComponent();}protected async override void OnNavigatedTo(NavigationEventArgs e){List<Task> tasks = new List<Task>();// 模拟 5 个线程并行执行,拿到许可证的线程才能运行,而许可证中心只有 2 个许可证for (int i = 0; i < 5; i++){CancellationToken token = new CancellationTokenSource().Token;Task task = Task.Run(() =>{OutMsg(string.Format("task {0} 等待一个许可证", Task.CurrentId));token.WaitHandle.WaitOne(5000);// WaitOne() - 申请许可证_semaphore.WaitOne();OutMsg(string.Format("task {0} 申请到一个许可证", Task.CurrentId));token.WaitHandle.WaitOne(1000);OutMsg(string.Format("task {0} 归还了一个许可证", Task.CurrentId));// int Release() - 归还许可证,返回值为:Release() 之前许可证中心可用的许可证数量int ignored = _semaphore.Release();// int Release(int releaseCount) - 指定释放的信号量的次数(按本文的理解就是指定归还的许可证数量)},token);tasks.Add(task);}await Task.WhenAll(tasks);}private void OutMsg(string msg){var ignored = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => {lblMsg.Text += msg;lblMsg.Text += Environment.NewLine;});}}}