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.

  • 相关阅读:
    ojdbc15-10.2.0.4.0.jar maven 引用报错 Dependency 'com.oracle:ojdbc15:10.2.0.4.0' not found
    两个js文件之间函数互调问题
    Win10连接远程桌面时提示“您的凭据不工作”
    Examples_08_03
    ant打包命令
    SVN版本日志对话框命令使用指南
    activiti_SpringEnvironment
    shell脚本
    python爬虫
    php正则表达式总结
  • 原文地址:https://www.cnblogs.com/zbw911/p/2442519.html
Copyright © 2011-2022 走看看