我目前正在开发一个从套接字读取 dat 的应用程序。
我很好奇,如果我有一个readDone.WaitOne(600000)
比正常超时更大的超时,如果由于回调方法中的异常而readDone.Set()
在我的方法中从未调用过会发生什么?ReadCallBack
它是等待整个超时持续时间,还是通过处理在 ? 之外定义的异常继续执行主线程ReadcallBack
?
编辑
这是一个例子来解释我的意思:
public void SendAndReceive(Message message)
{
try
{
IPAddress ipAddress = IPAddress.Parse(this.host.Address);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, this.host.Port);
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne(host.Timeout);
message.State = MessageState.SENDING;
Send(client, message.Request);
if (sendDone.WaitOne(120000)) // TIMEOUT SET TO 2 MINUTE
{
// Request sent successful. Now attempt to retrieve response.
message.State = MessageState.READING;
Receive(client);
}
else
{
message.State = MessageState.SEND_ERROR;
message.ErrorMessage = "Timeout while sending request to socket.";
}
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
catch (Exception ex)
{
LogManager.ExceptionHandler(ex);
message.ErrorMessage = ex.Message;
message.State = MessageState.EXCEPTION;
}
}
private void Send(Socket client, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
System.IO.MemoryStream dataStream = new System.IO.MemoryStream();
dataStream.WriteByte(1);
dataStream.Write(byteData, 0, byteData.Length);
dataStream.WriteByte(3);
client.BeginSend(dataStream.GetBuffer(), 0, dataStream.GetBuffer().Length, 0, new AsyncCallback(SendCallback), client);
}
private void SendCallback(IAsyncResult ar)
{
try
{
var client = (Socket)ar.AsyncState;
client.EndSend(ar);
// Throw exception before .Set can is called
throw new Exception("test");
sendDone.Set();
}
catch (Exception ex)
{
}
}
所以澄清一下:
sendDone.WaitOne(120000) 设置为 2 分钟后超时,这意味着 .Set() 在 2 分钟内没有被调用,主线程将继续执行。我的问题是,如果 SendCallBack 在调用 .Set() 之前存在异常,sendDone 是否仍会阻塞主线程 2 分钟,还是会自动跳转到 SendAndReceive 方法中的 try catch?