简要介绍:
1.定义异步执行需要调用的方法
2.定义具有与异步执行方法相同签名的委托(Delegate);
3.调用 BeginInvoke 和 EndInvoke 方法。
   3.1. BeginInvoke 方法用于启动异步调用。它与需要异步执行的方法具有相同的参数,
       只不过还有两个额外的参数。BeginInvoke 立即返回,不等待异步调用完成。
       BeginInvoke 返回 IasyncResult,可用于监视调用进度。
   3.2. EndInvoke 方法用于检索异步调用结果。调用 BeginInvoke 后可随时调用 EndInvoke 方法;
       如果异步调用未完成,EndInvoke 将一直阻塞到异步调用完成。
       EndInvoke 的参数包括需要异步执行的方法的 out 和 ref 参数以及由 BeginInvoke 返回的 IAsyncResult。
   3.3.调用了 BeginInvoke 后,可以:
      * 进行某些操作,然后调用 EndInvoke 一直阻塞到调用完成。
      * 使用 IAsyncResult.AsyncWaitHandle 获取 WaitHandle,使用它的 WaitOne 方法将执行一直阻塞到发出 WaitHandle 信号,然后调用 EndInvoke。
      * 轮询由 BeginInvoke 返回的 IAsyncResult,确定异步调用何时完成,然后调用 EndInvoke。
      * 将用于回调方法的委托传递给 BeginInvoke。该方法在异步调用完成后在 ThreadPool 线程上执行,它可以调用 EndInvoke。

//具体代码如下:

using System;
using System.Threading;

//The example of using delegate
namespace DelegateCallAsynchronousMethods
{

class AsyncFileDelegate
   {
       /*
        *这是需要异步执行的方法,COPY一个文件
        */
        public void CopyFile(String fileName, out bool result)
        {
            Console.WriteLine("Move file "+fileName+"...");
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(200);
                Console.WriteLine("Move file is running..." + i);
            }
            Console.WriteLine("Move file finished");
            result = true;
        }
       
       /*
        *定义COPY文件的委托,将来CopyFile方法就委托给它去异步执行
        */
        public delegate void CopyFileDelegate(String fileName, out bool result);//Declare copy file delegate

static void Main()
       {
            bool result;
            AsyncFileDelegate aa = new AsyncFileDelegate();
            // 开始委托方法,以后都由copyFile这个变量来做事
            CopyFileDelegate copyFile = new CopyFileDelegate(aa.CopyFile);

Console.WriteLine("[Main] Invoking the asynchronous "+" Copy file method");
            //委托调用异步方法去执行
            IAsyncResult iAR = copyFile.BeginInvoke("songlin.txt", out result, null, null);

// 主方法不用等待COPY FILE方法,继续自己的事情
            Console.WriteLine("[Main] Doing other work");
            for (int i = 0; i < 10; i++)
           {
                Thread.Sleep(200);
                Console.WriteLine("[Main]MainMethod is running..."+i);
            }
           
           
            Console.WriteLine(" [Main] Waiting for file transformation to finish");
            /* 主方法自己的事情做完,开始检查COPYFILE有没有完成。
             * 使用它的 WaitOne 方法将执行一直等到发出 WaitHandle 信号,然后调用 EndInvoke。
             * 注意:异步调用完成时会发出 WaitHandle 信号,可以通过WaitOne 来等待它*/
            iAR.AsyncWaitHandle.WaitOne();

Console.WriteLine("[Main] Copy file finished, cleaning up");
            /* EndInvoke 方法用于检索异步调用结果。调用 BeginInvoke 后可随时调用 EndInvoke 方法;
             * 如果异步调用未完成,EndInvoke 将一直阻塞到异步调用完成。
             */
            copyFile.EndInvoke(out result, iAR);

Console.WriteLine("[Main] The result is {0}", result);
            Console.ReadLine();
        }
    };

}

下面是输出结果,可以看出copyfile方法和主方法是异步执行的。
----------------------------------------------------------------------------------------------
[Main] Invoking the asynchronous Copy file method
[Main] Doing other work
Move file songlin.txt...
[Main]MainMethod is running...0
Move file is running...0
[Main]MainMethod is running...1
Move file is running...1
[Main]MainMethod is running...2
Move file is running...2
[Main]MainMethod is running...3
Move file is running...3
[Main]MainMethod is running...4
Move file is running...4
[Main]MainMethod is running...5
Move file is running...5
[Main]MainMethod is running...6
Move file is running...6
[Main]MainMethod is running...7
Move file is running...7
[Main]MainMethod is running...8
Move file is running...8
[Main]MainMethod is running...9
[Main] Waiting for file transformation to finish
Move file is running...9
Move file finished
[Main] Copy file finished, cleaning up
[Main] The result is True

以下是代码例子,模拟了文件拷贝。每个文件的拷贝方法都是在异步方式下运行,同时主方法依然运行。

在主方法的最后会等待直到所有的异步方法执行完成。

namespace WindowsApplication2

{

public class AsyncFileCopy

{

//Declare copy file delegate, will use this to invoke real copy file method

public  delegate string CopyFileDelegate(int fileSize);

//The real file copy method, we simulate file copy with thread sleep

public String CopyFile(int fileSize)

{

switch (fileSize)

{

case 1:

Console.WriteLine("File 1 copy start...");

Thread.Sleep(1000);

Console.WriteLine("File 1 copy finished");

return "One";

case 2:

Console.WriteLine("File 2 copy Start...");

Thread.Sleep(2000);

Console.WriteLine("File 2 copy Finished");

return "Two";

case 3:

Console.WriteLine("File 3 copy  Start...");

Thread.Sleep(3000);

Console.WriteLine("File 3 copy Finished");

return "Three";

default:

return "default";

}

}

public void ExecuteCopy()

{

List<WaitHandle> list = new List<WaitHandle>();

Console.WriteLine("Main method Start");

//Init coyp file delegate

CopyFileDelegate dlg = new CopyFileDelegate(CopyFile);

//Assume we have 4 different size files.

//Section below will let each file be copied in Async model

for (int i = 0; i < 4; i++)

{

//Let copy file executed in Async model, main thread continue

IAsyncResult ar = dlg.BeginInvoke(i, null, null);

list.Add(ar.AsyncWaitHandle);

Console.WriteLine("Main method still working" + i);

Thread.Sleep(10);//simulate main method cost some time

}

//Ensure all Async method finished before return from main method

System.Threading.WaitHandle.WaitAll(list.ToArray());

Console.WriteLine("Main method finished");

}

public static void Main(string[] args)

{

AsyncFileCopy test = new AsyncFileCopy();

test.ExecuteCopy();

}

}

}

ASP.NET 委托,异步调用例子 .的更多相关文章

  1. C#委托异步调用

    参考页面: http://www.yuanjiaocheng.net/webapi/mvc-consume-webapi-get.html http://www.yuanjiaocheng.net/w ...

  2. 委托-异步调用-泛型委托-匿名方法-Lambda表达式-事件【转】

    1. 委托 From: http://www.cnblogs.com/daxnet/archive/2008/11/08/1687014.html 类是对象的抽象,而委托则可以看成是函数的抽象.一个委 ...

  3. 那些年我们一起追逐的多线程(Thread、ThreadPool、委托异步调用、Task/TaskFactory、Parallerl、async和await)

    一. 背景 在刚接触开发的头几年里,说实话,根本不考虑多线程的这个问题,貌似那时候脑子里也有没有多线程的这个概念,所有的业务都是一个线程来处理,不考虑性能问题,当然也没有考虑多线程操作一条记录存在的并 ...

  4. asp.net中异步调用WebService(异步页)[转]

    由于asp2.0提供了异步页的支持使异步调用WebService的性能有了真正的提升.使用异步页,首先要设置Async="true",异步页是在Prerender和Prerende ...

  5. 异步和多线程,委托异步调用,Thread,ThreadPool,Task,Parallel,CancellationTokenSource

    1 进程-线程-多线程,同步和异步2 异步使用和回调3 异步参数4 异步等待5 异步返回值 5 多线程的特点:不卡主线程.速度快.无序性7 thread:线程等待,回调,前台线程/后台线程, 8 th ...

  6. asp.net中异步调用webservice

    WebService方法是不需要作任何修改的,只是在调用时采用异步的方式,这样在循环中,速度会显得快一点. 原来的方式: HotelMagWeb.com.china_sms.www.MainServi ...

  7. c# 委托与异步调用

    背景:在winform UI中,有时需要对控件进行比较频繁的刷新,如进度条.picturebox显示视频等.如果在主线程进行这些刷新操作,操作还未完成就将执行下一次刷新,程序将发生错误:如果只是创建另 ...

  8. C# 多线程详解 Part.02(UI 线程和子线程的互动、ProgressBar 的异步调用)

           我们先来看一段运行时会抛出 InvalidOperationException 异常的代码段: private void btnThreadA_Click(object sender, ...

  9. [置顶] Ajax程序:处理异步调用中的异常(使用Asp.Net Ajax内建的异常处理方法)

    无论在Window应用程序,还是Web应用程序以对用户友好的方式显示运行时的异常都是很有必要,尤其对于可能有很多不确定因素导致异常的Web应用程序;在传统的Web开发中,处理异常的方式——设计专门一个 ...

随机推荐

  1. hdu 2079 选课时间_母函数

    题意:需要学够n学分,有k个情况(x学分,y个相同学分的课) 解法:套母函数模板 #include <iostream> #include<cstdio> using name ...

  2. CSS3初步

    一.CSS与CSS3的区别 非常简单,CSS代表"Casading Style Sheets",就是样式表,是一种替代并为网站添加样式的标记性语言.现在所使用的CSS基本是在199 ...

  3. FreeMarker的模板文件语法

    FreeMarker的模板文件并不比HTML页面复杂多少,FreeMarker模板文件主要由如下4个部分组成: 1,文本:直接输出的部分 2,注释:<#-- ... -->格式部分,不会输 ...

  4. Clash of Clans(COC)资源压缩解密

    Clash of Clans,简称为COC,中文名<部落冲突>,是ios平台上一款相当火爆的战斗策略类游戏,开发商是芬兰的supercell,据说日收入上百万美刀,创造了手游史上的一个神话 ...

  5. 449A - Jzzhu and Chocolate 贪心

    一道贪心题,尽量横着切或竖着切,实在不行在交叉切 #include<iostream> #include<stdio.h> using namespace std; int m ...

  6. ubuntu下安装xlrd模块,Mysqldb模块

    Python中安装xlrd模块 1.从 https://pypi.python.org/pypi/xlrd  下载压缩包 2.解压所下载的压缩包 3.CD到解压文件夹,运行 sudo python s ...

  7. 利用iptables将本地的80端口请求转发到8080,当前主机ip为192.168.1.1,命令怎么写?

    iptables -t nat -A PREROUTING -d 192.168.1.1 -p tcp --dport 80 -j REDIRECT --to-port 8080 内网上外网: ipt ...

  8. 疯狂Android第一章:Android环境配置以及基本概念

    第一章 无关痒痛:Android Studio安装,配置,基本功能介绍! 重点内容:Android应用基本结构分析. 基础概念部分(只需知道作用,原理后见代码): Activity:安卓系统中负责与用 ...

  9. 单链表(Single Linked List)

    链表的结点结构  ┌───┬───┐  │data|next│  └───┴───┘ data域--存放结点值的数据域 next域--存放结点的直接后继的地址(位置)的指针域(链域) 实例:从终端输入 ...

  10. Qt WebEngine 网页交互

    环境:Qt5.7.0,VS2013 一.简单介绍 从 Qt5.4 开始已经去掉 Qt WebKit 模块了,使用的是 chrome 内核封装的 QtWebEngine,浏览器相关的类有以下几个: QW ...