如何捕获事件中的异常???

yellowwee 2011-04-14 11:12:15
SendCMD中throw的能捕获,OnSend中不行。怎么回事?


private string SendCMD(string message)
{
throw new Exception("eeee");
sendBuffer = Encoding.Default.GetBytes(message);

//Prepare arguments for send/receive operation.
SocketAsyncEventArgs completeArgs = new SocketAsyncEventArgs();
completeArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
completeArgs.UserToken = clientSocket;
completeArgs.RemoteEndPoint = hostEndPoint;
completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);

//Start sending asyncronally.
clientSocket.SendAsync(completeArgs);

//Wait for the send/receive completed.
AutoResetEvent.WaitAll(autoSendReceiveEvents);

//Return data from SocketAsyncEventArgs buffer.
string sReturn = Encoding.Default.GetString(completeArgs.Buffer, completeArgs.Offset, completeArgs.BytesTransferred);

return sReturn;
}

//OnSend方法使用
private byte[] receiveBuffer = new byte[4096];

private void OnSend(object sender, SocketAsyncEventArgs e)
{
throw new Exception();

autoSendReceiveEvents[RecevieOperation].Set();

if (e.SocketError == SocketError.Success)
{
if (e.LastOperation == SocketAsyncOperation.Send)
{
//Prepare receiving.
Socket s = e.UserToken as Socket;
if (s != null)
{
//throw new OutOfMemoryException();
e.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);

s.ReceiveAsync(e);
}
}
}
else
{
ProcessError(e);
}
}
...全文
150 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
线程不抛出异常。

如果一定要“捕获”,你可以在线程所执行的方法的接口上使用一个回调Action<Exception>类型的参数来处理。
马少华 2012-05-11
  • 打赏
  • 举报
回复
外面处理不了,就在方法里面处理
yellowwee 2011-04-21
  • 打赏
  • 举报
回复
没答案
gomoku 2011-04-14
  • 打赏
  • 举报
回复
异常处理是基于栈进行的。因此它可以捕获当前线程的异常,却不能直接捕获其他线程的异常。

注意你代码中的SendAsync(异步发送)。
yellowwee 2011-04-14
  • 打赏
  • 举报
回复
那怎么才能处理这个异常呢?

111,097

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧