委托 delegate ----同步、异步

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Threading;

using System.Runtime.Remoting.Messaging;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        /*

         *实际上,当我们通过声明一个delegate并调用该方法的时候,我们是调用Invoke方法。

         *系统在执行完该方法之后再返回,整个过程是一个同步调用,系统在执行delegate代码的时候会等待该部分执行完再继续,

         *而且所有这些代码的执行是在同一个线程里面。

         *如果我们要通过异步调用来执行delegate的话,则需要使用BeginInvoke和EndInvoke方法,这样delegate代码是在另外一个线程中执行,

         *这样我们的代码就是一个多线程执行的过程。

        */

 

 

        public delegate void myDelegate(string str);

        public void doSth(string str)

        {

            MessageBox.Show("Delegate的线程ID:" + Thread.CurrentThread.ManagedThreadId.ToString());

            Thread.Sleep(2000);

            MessageBox.Show(str);

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            MessageBox.Show("开始执行....");

            MessageBox.Show("窗体的线程ID:" + Thread.CurrentThread.ManagedThreadId.ToString());

            myDelegate myd = new myDelegate(doSth);

            //这样是执行同步操作,窗体的线程ID跟delegate的线程ID是一样的

            //myd("测试");

 

            //如果要获取函数调用返回的结果,我们就通过EndInvoke方法以BeginInvoke方法的结果作为参数。

            //通过了BeginInvoke窗体的线程ID跟delegate的线程ID是不一样的

            //IAsyncResult iftAR = myd.BeginInvoke("测试", null, null);

            //myd.EndInvoke(iftAR);

 

            //先执行delegate,然后执行AsnycCallBack,  "abc"是AsyncState,一个自定义的数据

            //当我们启动一个异步delegate执行的时候,我们想要知道它执行的怎么样了,什么时候执行完。

            //我们可以定义一个AsyncCallback类型的方法,在异步delegate执行的时候调用该方法来通知调用线程。

            //而对于object参数,这是用来提供一些自定义的数据的。自定义一些数据然后AddComplete方法来访问它,itfAR.AsyncState就包含了自定义数据

 

            IAsyncResult iftAR = myd.BeginInvoke("测试", AddTest, "abc");

        }

 

 

        static void AddTest(IAsyncResult itfAR)

        {

            MessageBox.Show("AddTest方法的线程ID:" + Thread.CurrentThread.ManagedThreadId.ToString());

 

            //得到委托方法的结果

            AsyncResult ar = (AsyncResult)itfAR;

            myDelegate my = (myDelegate)ar.AsyncDelegate;

            my.EndInvoke(itfAR);

 

            string msg = (string)itfAR.AsyncState;

            MessageBox.Show(msg);//输出abc

        }

 

    }

posted @ 2010-09-16 17:00  英雄不问出处  阅读(301)  评论(0编辑  收藏  举报