子曾经曰过

  博客园  :: 首页  ::  ::  ::  :: 管理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;

namespace DelegateStudyWell
{

class AsyncCall
{
public delegate void ChatEventHandler(object sender, ChatEventArgs e);
public static event ChatEventHandler ChatEvent;
public static ChatEventHandler myEventHandler;

static void Main(string[] args)
{
ChatEventArgs eva
= new ChatEventArgs();
eva.message
= "hello";

myEventHandler
= new ChatEventHandler(MyEventHandler);
ChatEvent
+= myEventHandler; //不是订阅事件,而是事件相加组成一个委托链

new AsyncCall().BroadCast(eva);

Console.ReadLine();
}
private static void MyEventHandler(object sender, ChatEventArgs e)
{
Console.WriteLine(e.message);
}

public void BroadCast(ChatEventArgs e)
{
ChatEventHandler temp
= ChatEvent; //可以直接这样写?什么意思?
if (temp != null)
{
foreach (ChatEventHandler handler in temp.GetInvocationList())
{ handler.BeginInvoke(
this, e, new AsyncCallback(EndAsync), null); }
//handler此时已经和方法MyEventHandler绑定在了一起?如何做到的?

//委托异步调用的返回值类型是IAsyncResult
//这边只要开始调用,EndAsync中的参数 ar 就已经有相关的值了
//换句话讲,这个EndAsync函数的参数并不是我们可以控制的,
//随着异步调用的进行,这个参数可能也有些变化
//是不是可以这样理解,如果要进行异步调用,就要显式的定义这样个参数已经确定的函数?

}
}
public void EndAsync(IAsyncResult ar) //ar这个参数是handler.BeginInvoke和下面这个EndAsync关联的纽带
{
ChatEventHandler d
= null;
AsyncResult asres
= (AsyncResult)ar;


//Console.WriteLine(asres.AsyncDelegate.GetType().ToString());
d = ((ChatEventHandler)asres.AsyncDelegate); //asres.AsyncDelegate获取的是handler
//Console.WriteLine(d.GetType().ToString());
Console.WriteLine("主线程在执行异步调用时候这边可以同时进行的操作");
d.EndInvoke(ar);
//有没有这一句有什么区别呢?

}
}


public class ChatEventArgs : EventArgs
{
public string message;
}
}
posted on 2011-03-04 14:40  人的本质是什么?  阅读(270)  评论(0编辑  收藏  举报