zoukankan      html  css  js  c++  java
  • 异步委托(APM)使用Func异步操作,处理耗时操作

    使用委托进行异步操作,处理一些耗时操作,防止主线程阻塞

    使用例子:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace Demo
     7 {
     8     class Program
     9     {
    10 
    11         static void Main(string[] args)
    12         {
    13             Func<string> fun = new Func<string>(Test);   
    14             Console.WriteLine("异步执行开始(异步委托的方法):" + fun.Method);
    15            IAsyncResult asyncResult= fun.BeginInvoke(CallBack,new string []{"sadha","sahsiuh"});  //开始异步操作
    16 
    17             for (int i = 0; i < 10;i++ )
    18             {
    19                 Console.WriteLine("异步方法执行时同时执行其它代码:"+i);
    20             }
    21 
    22             fun.EndInvoke(asyncResult);  //结束异步
    23             Console.ReadKey();
    24         }
    25 
    26         /// <summary>
    27         /// 异步执行的方法
    28         /// </summary>
    29         /// <returns></returns>
    30         public static string Test()
    31         {
    32             return DateTime.Now.ToString();
    33         }
    34 
    35         /// <summary>
    36         /// 异步方法执行完成回掉的方法
    37         /// </summary>
    38         /// <param name="async"></param>
    39         public static void CallBack(IAsyncResult async)
    40         {
    41             string [] array= async.AsyncState as string [];
    42             Console.WriteLine("异步操作是否完成:"+ async.IsCompleted);
    43         }
    44     }
    45 }

    上述代码运行结果:

  • 相关阅读:
    HUST 1584 摆放餐桌
    HUST 1585 排队
    HUST 1583 长度单位
    树状数组 poj2352 Stars
    Visual Studio2013应用笔记---WinForm事件中的Object sender和EventArgs e参数
    倒置输入的数 Exercise07_02
    指定等级 Exercise07_01
    检测密码 Exercise06_18
    一年的天数 Exercise06_16
    数列求和 Exercise06_13
  • 原文地址:https://www.cnblogs.com/linJie1930906722/p/5661944.html
Copyright © 2011-2022 走看看