0
我目前正在從套接字讀取數據的應用程序。異常後的WaitOne(超時)
我很好奇,如果我有一個大於正常超時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)
{
}
}
所以澄清:被設置在2分鐘後超時
sendDone.WaitOne(120000),這意味着,Set()在2分鐘內不會被調用,主線程將繼續執行。我的問題是,如果在調用Set()之前SendCallBack中存在和異常,那麼sendDone仍會佔用主線程2分鐘,還是會自動跳到SendAndReceive方法中的try catch?
你的問題對我來說很不清楚。你爲什麼期望它不會等待完整的超時? –
郵政編碼,我們會更好地回答這個問題 – BlackICE