异常后的WaitOne(超时)

时间:2013-05-29 07:26:36

标签: c# sockets

我正在开发一个从套接字读取数据的应用程序。

我很好奇,如果我有超过正常超时的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分钟后设置为超时,这意味着,在2分钟内未调用.Set()主线程将继续执行。我的问题是,如果在调用.Set()之前SendCallBack中存在异常,sendDone是否仍会将主线程保持2分钟,还是会自动跳转到SendAndReceive方法中的try catch?

1 个答案:

答案 0 :(得分:0)

所以我测试了这个,如果抛出异常,WaitOne()就会被取消。