本文只要参考了 Chapter 6's EventsEnhanced sample here
主要是改良了EventsEnhanced
1:生成窗体式客户端
2:服务器端加上线程控制
工作原理:
客户端发送一个信息到服务器端,服务器端把该信息发送给所有在线的客户端
客户端界面:
服务器端:
foreach (Delegate del in MessageArrived.GetInvocationList()) {
mah = (MessageArrivedHandler) del;
//线程类
ThreadDataContainer tdc = new ThreadDataContainer(msg, mah);
//线程发送失败时的操作
tdc.SendFalse += new SendFalseHandler(MessageArrivedDelete);
//启动线程
Thread thread1 = new Thread(new ThreadStart(tdc.ThreadTask));
thread1.Start();
}
线程类:
//由于线程不能直接传递参数,和线程不能返回参数到主进程中
//所以要建立一个类,来获得线程所需要的参数.
//线程要返回参数到主进程,通过事件的引发,即可实现.
//当线程异常的时候,引发事件.
public delegate void SendFalseHandler(MessageArrivedHandler mah);
public class ThreadDataContainer
{
public AutoResetEvent threadDone = new AutoResetEvent(false);
MessageArrivedHandler mah;
string msg;
//发送失败事件
public event SendFalseHandler SendFalse;
public ThreadDataContainer(string msg, MessageArrivedHandler mah)
{
this.msg = msg;
this.mah = mah;
}
public void ThreadTask()
{
try
{
mah(msg);
}
catch(Exception e)
{
if(SendFalse!=null)
SendFalse(mah);
}
}
}