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.

  • 相关阅读:
    webstorm 2017 激活破解 最新 2018
    phpexcel 导出xsl乱码
    微信小程序的z-index在苹果ios无效
    onenote架设在局域网服务器
    .gitignore忽略多层文件夹用**
    phpstorm 使用xdebug断点
    Phpstudy 无法启动mysql
    git使用kdiff3合并乱码问题
    小程序回退刷新操作
    Navicat 连接远程服务器mysql 长时间不操作会连接很久
  • 原文地址:https://www.cnblogs.com/zbw911/p/2442519.html
Copyright © 2011-2022 走看看