110,529
社区成员
发帖
与我相关
我的任务
分享
void AcceptClientCallBack(IAsyncResult iar)
{
try
{
TcpListener listener = (TcpListener)iar.AsyncState;
//获得客户端;
this.Tcpclient = new MyTcpClient(listener.EndAcceptTcpClient(iar));
}
catch(Exception ex)
{
this.Tcpclient = null;
return;
}
// 这里是主要内容
}
你的代码的主要工作内容,应该在 catch 之后,而不是在try 之内。这里的 try....catch 应该准确地就是为了 listener.EndAcceptTcpClient(iar) 这一个东西而设计的。实际上 try 包含了你的 new MyTcpClient(...) 这样一个语句,都有一点范围扩大了。不过假设你这个对象实例化也没有做什么容易发生问题的事情,暂且可以这样写。
也就是说,try...catch 不要随便扩大。void AcceptClientCallBack(IAsyncResult iar)
{
TcpClient client = null;
try
{
TcpListener listener = (TcpListener)iar.AsyncState;
client = listener.EndAcceptTcpClient(iar);
}
catch(Exception ex)
{
this.Tcpclient = null;
return;
}
this.Tcpclient = new MyTcpClient(client);
//........................继续进行处理
}
void AcceptClientCallBack(IAsyncResult iar)
{
TcpClient client = null;
try
{
TcpListener listener = (TcpListener)iar.AsyncState;
client = listener.EndAcceptTcpClient(iar);
}
catch(Exception ex)
{
this.Tcpclient = null;
return;
}
this.Tcpclient = new MyTcpClient(client);
}
这样就能明白地说明你的逻辑了,别人也就不会误解你使用 try,,,catch 的本意了。
之所以误解,就是因为你任意夸大了 try...catch 的适用范围,上纲上线,因此触碰了基本的原则。