zoukankan      html  css  js  c++  java
  • 两段小代码

    private Action<int> sleep = second =>
               {
                   Console.WriteLine("enter Action");
                   Thread.Sleep(second * 1000);

                   PrintThread();

                   Console.WriteLine("leave Action");
               };

    public void AsynT()
           {
               PrintThread();
               Console.WriteLine("begin");

               var result = sleep.BeginInvoke(2, null, null);

               Console.WriteLine("continue");

               sleep.EndInvoke(result);

               Console.WriteLine("end");
           }

           public void AsynOption()
           {
               PrintThread();
               var waiter = new ManualResetEvent(false);

               Console.WriteLine("begin");
               sleep.BeginInvoke(2, callback =>
               {
                   //callback.AsyncWaitHandle.WaitOne();
                   Console.WriteLine("end");
                   sleep.EndInvoke(callback);
                   waiter.Set();
               }, null);

               Console.WriteLine("continue");

               waiter.WaitOne();

               //Console.Read();
           }

    在执行第二个方法的时候,我们可以会发现,如果去掉 ManualResetEvent 以后, callback代码不执行了。这是为什么呢?

    经过仔细研究后,发现,

    sleep.BeginInvoke(2, callback =>

    相当于

    sleep.BeginInvoke(2,new AsynCallback(…..)…..

    使用回调方法。

    从MSDN查到原因如下:

    The callback is made on a ThreadPool thread. ThreadPool threads
    are background threads, which do not keep the application running
    if the main thread ends.

  • 相关阅读:
    新增数据盘
    FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。
    将tomcat的protocol改为APR模式,以提高性能
    POJ 2195 Going Home (最小费用最大流)
    HDU 2732 Leapin' Lizards (最大流)
    POJ 2516 Minimum Cost (最小费用最大流)
    POJ 1087 A Plug for UNIX (最大流)
    POJ 3281 Dining (最大流)
    HDU 3605 Escape (最大流)
    POJ 1149 PIGS (最大流)
  • 原文地址:https://www.cnblogs.com/zbw911/p/2442519.html
Copyright © 2011-2022 走看看