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.

  • 相关阅读:
    C#中的Singleton模式
    CodeLib
    Google Chats 居然和Gmail集成了...
    Windows中OSG环境搭建
    Socket中winsock.h和winsock2.h的不同
    高斯日记 蓝桥杯
    MATLAB矩阵处理
    马虎的算式 蓝桥杯
    MATLAB基础
    矩阵相乘的一维数组实现
  • 原文地址:https://www.cnblogs.com/zbw911/p/2442519.html
Copyright © 2011-2022 走看看