码迷,mamicode.com
首页 > 其他好文 > 详细

ManualResetEvent & AutoResetEvent

时间:2015-01-15 20:14:49      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

ManualResetEvent和AutoResetEvent的作用可以理解为在线程执行中插入停顿点flag终止程序运行,然后通过设置flag的状态来使得程序继续运行。

两者的区别是:ManualResetEvent设置flag状态为可以运行后,所有在终止点的程序都可以继续运行;AutoResetEvent设置flag状态后,只会有一个程序继续运行(如果AutoResetEvent设置的flag有100个程序在等待,那flag开始状态必须要设置100次才能使得所有的线程都执行完毕)

示例如下(ManualResetEvent时会同时执行三个线程,AutoResetEvent则会依次执行):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data;

public class Example
{

    /// <summary>

    /// 预备信号,准备发送,初始化

    /// </summary>

    public EventWaitHandle flag;
    public void Begin()
    {
        //flag = new ManualResetEvent(false);
        flag = new AutoResetEvent(false);
        Thread th1 = new Thread(() =>
        {
            flag.WaitOne();
             Thread.Sleep(1000);
           Console.WriteLine("第一个线程已经通过……");
            flag.Set();

        });



        Thread th2 = new Thread(() =>
        {
            flag.WaitOne();
             Thread.Sleep(1000);
           Console.WriteLine("第二个线程已经通过……");
            flag.Set();

        });


        Thread th3 = new Thread(() =>
        {
            flag.WaitOne();
            Thread.Sleep(1000);
            Console.WriteLine("第三个线程已经通过……");
           flag.Set();

        });

        th1.IsBackground = true;
         th1.Start();
         th2.IsBackground = true;
         th2.Start();
        th3.IsBackground = true;
         th3.Start();
         flag.Set();
        Thread.Sleep(1000);
 
        Console.WriteLine("A");
        Console.WriteLine("B");

    }



    static void Main(string[] args)
    {
        new Example().Begin();
        Console.ReadKey();
    }
}

 

ManualResetEvent & AutoResetEvent

标签:

原文地址:http://www.cnblogs.com/thaughtZhao/p/4227079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!