zoukankan      html  css  js  c++  java
  • C# AutoResetEvent

    原文链接:http://dotnetpattern.com/threading-autoresetevent

    AutoResetEvent是.net线程简易同步方法中的一种。

    AutoResetEvent 常常被用来在两个线程之间进行信号发送

       两个线程共享相同的AutoResetEvent对象,线程可以通过调用AutoResetEvent对象的WaitOne()方法进入等待状态,然后另外一个线程通过调用AutoResetEvent对象的Set()方法取消等待的状态。

    AutoResetEvent如何工作的

       在内存中保持着一个bool值,如果bool值为False,则使线程阻塞,反之,如果bool值为True,则使线程退出阻塞。当我们创建AutoResetEvent对象的实例时,我们在函数构造中传递默认的bool值,以下是实例化AutoResetEvent的例子。

    AutoResetEvent autoResetEvent = new AutoResetEvent(false);
    WaitOne 方法

    该方法阻止当前线程继续执行,并使线程进入等待状态以获取其他线程发送的信号。WaitOne将当前线程置于一个休眠的线程状态。WaitOne方法收到信号后将返回True,否则将返回False。

    autoResetEvent.WaitOne();

    WaitOne方法的第二个重载版本是等待指定的秒数。如果在指定的秒数后,没有收到任何信号,那么后续代码将继续执行。

    复制代码
    static void ThreadMethod()
    {
        while(!autoResetEvent.WaitOne(TimeSpan.FromSeconds(2)))
        {
            Console.WriteLine("Continue");
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
     
        Console.WriteLine("Thread got signal");
    }
    复制代码

    这里我们传递了2秒钟作为WaitOne方法的参数。在While循环中,autoResetEvent对象等待2秒,然后继续执行。当线程取得信号,WaitOne返回为True,然后退出循环,打印"Thread got signal"的消息。

    Set 方法

    AutoResetEvent Set方法发送信号到等待线程以继续其工作,以下是调用该方法的格式。

    autoResetEvent.Set();

    AutoResetEvent例子

    下面的例子展示了如何使用AutoResetEvent来释放线程。在Main方法中,我们用Task Factory创建了一个线程,它调用了GetDataFromServer方法。调用该方法后,我们调用AutoResetEvent的WaitOne方法将主线程变为等待状态。在调用GetDataFromServer方法时,我们调用了AutoResetEvent对象的Set方法,它释放了主线程,并控制台打印输出dataFromServer方法返回的数据。

    复制代码
    class Program
    {
        static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
        static string dataFromServer = "";
     
        static void Main(string[] args)
        {
            Task task = Task.Factory.StartNew(() =>
            {
                GetDataFromServer();
            });
     
            //Put the current thread into waiting state until it receives the signal
            autoResetEvent.WaitOne();
     
            //Thread got the signal
            Console.WriteLine(dataFromServer);
        }
     
        static void GetDataFromServer()
        {
            //Calling any webservice to get data
            Thread.Sleep(TimeSpan.FromSeconds(4));
            dataFromServer = "Webservice data";
            autoResetEvent.Set();
        }
    }
    复制代码
    版权声明:本博客所有图片、文字等版权属于虫子樱桃所有,未经许可谢绝任何形式的复制和传播。博客的图片和代码部分来自网络,本站均已注明来源和作者原来的声明。如有侵权,请使用本站联系方式告诉,我们将会在第一时间做出处理。
  • 相关阅读:
    网络多线程 ---实现网络负载图片
    optimizer for eclipse--Eclipse优化,让你的Eclipse快来飞!
    ORACLE AUTOMATIC STORAGE MANAGEMENT翻译-第二章 ASM instance(1)
    IOS 开展 分别制定了iphone 和 ipad 好? 或开发一个 Universal好?
    DevExpress VCL 2014.1.2 for C++BUILDER XE6
    swift http请求返回json数据和分析
    Spark里面的任务调度:离SparkContext开始
    ftk学习记录(一个进度条文章)
    Appium Android Bootstrap控制源代码的分析AndroidElement
    别忽视了业绩比较基准
  • 原文地址:https://www.cnblogs.com/asdyzh/p/9944221.html
Copyright © 2011-2022 走看看