zoukankan      html  css  js  c++  java
  • (二)线程通过委托异步调用方法

     

    (一).描述
      先运行个简单的线程示例,认识一下线程
      通过委托调用方法,以及使用AsyncResult判断线程的状态

    (二).代码
    using System;
    using System.Threading;
    using System.Runtime.Remoting.Messaging;

    namespace 通过委托异步调用方法

     
    //委托声明(函数签名)
     delegate string MyMethodDelegate();

     
    class MyClass
     
    {
      
    //要调用的动态方法
      public string MyMethod1()
      
    {
       
    return "Hello Word1";
      }


      
    //要调用的静态方法
      public static string MyMethod2()
      
    {
       
    return "Hello Word2";
      }

     }

     
    class Class1
     
    {
      
    /// <summary>
      
    /// 应用程序的主入口点。
      
    /// </summary>

      [STAThread]
      
    static void Main(string[] args)
      
    {
                MyClass myClass 
    = new MyClass();
       
       
    //方式1:  声明委托,调用MyMethod1
       MyMethodDelegate d = new MyMethodDelegate(myClass.MyMethod1);
       
    string strEnd = d();   
       Console.WriteLine(strEnd);

       
    //方式2:  声明委托,调用MyMethod2 (使用AsyncResult对象调用)
       d = new MyMethodDelegate(MyClass.MyMethod2); //定义一个委托可以供多个方法使用      
       AsyncResult myResult;   //此类封闭异步委托异步调用的结果,通过AsyncResult得到结果.
       myResult = (AsyncResult)d.BeginInvoke(null,null);        //开始调用
       while(!myResult.IsCompleted)  //判断线程是否执行完成
       {
        Console.WriteLine(
    "正在异步执行MyMethod2 ..");
       }

       Console.WriteLine(
    "方法MyMethod2执行完成!");
       strEnd 
    = d.EndInvoke(myResult);      //等待委托调用的方法完成,并返回结果  
       Console.WriteLine(strEnd);
       Console.Read();
      }

     }

    }

  • 相关阅读:
    MyBatis——调用存储过程
    企业信息化快速开发平台JeeSite
    JavaWeb网页聊天室(WebSocket即时通讯)
    Java用webSocket实现tomcat的日志实时输出到web页面
    Java用WebSocket + tail命令实现Web实时日志
    linux 跨IP拷贝命令 scp
    在map中根据value获取key
    mysql 常用函数
    Nexus中自定义私服,每个项目都用独立的工厂,仓库
    button 默认类型是submit
  • 原文地址:https://www.cnblogs.com/engine1984/p/862970.html
Copyright © 2011-2022 走看看