zoukankan      html  css  js  c++  java
  • c#的BeginInvoke和EndInvoke使用demo

    BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            private delegate int NewTaskDelegate(int ms,string msg);
            private static int newTask(int ms, string msg)
            {
                Console.WriteLine("任务开始");
                Thread.Sleep(ms);
                Random random = new Random();
                int n = random.Next(10000);
                Console.WriteLine("任务完成" + msg);
                return n;
            }
            static void Main(string[] args)
            {
                AsyncCallback asyncCallback = new AsyncCallback(MyAsyncCallback);
                NewTaskDelegate task = new NewTaskDelegate(newTask);
                IAsyncResult asyncResult = task.BeginInvoke(2000,"fk", asyncCallback, task);
    
                // EndInvoke方法将被阻塞2秒   
                //int result = task.EndInvoke(asyncResult);
                //Console.WriteLine(result);
                Console.ReadLine();
            }
            public static void MyAsyncCallback(IAsyncResult iar)
            {
                int str;
                NewTaskDelegate dlgt = (NewTaskDelegate)iar.AsyncState;
                str = dlgt.EndInvoke(iar);
                Console.WriteLine("the Delegate call returned string:{0}", str);
            }
        }
    
    
    }
    

      

  • 相关阅读:
    设计模式之观察者模式
    设计模式之建造者模式
    设计模式之外观模式
    设计模式之模板方法模式
    设计模式之原型模式
    自己动手写计算器v1.1
    自己动手写计算器v1.0
    Guid的使用
    设计模式学习---代理类
    StringBuilder的使用
  • 原文地址:https://www.cnblogs.com/wolfocme110/p/6869032.html
Copyright © 2011-2022 走看看