我有一个简单的代码,用于打开与设备的连接,使用它并在需要时重新连接:
Socket socket = null;
while (!terminated)
{
try
{
if (socket == null || !socket.Connected)
{
if (socket != null)
{
socket.Close(1000);
}
socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
socket.ReceiveTimeout = 1000;
socket.SendTimeout = 1000;
IAsyncResult awaitResult = socket.BeginConnect(ip, port, null, null);//trying to connect with timeout
if (awaitResult.AsyncWaitHandle.WaitOne(5000))
{
socket.EndConnect(awaitResult);
}
}
if (socket.Connected)
{
socket.Send(request);
Thread.Sleep(10);
read = socket.Receive(recieveBuffer);
//work with data
Thread.Sleep(250);
}
}
catch (SocketException)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close(1000); //hangs here
socket = null;
}
}
我在应用程序中有几个这样的专家。它们正常工作,甚至catch
块也是如此。但是每天发生几次(可能是网络故障),并且所有线程同时在Close(timeout)
块中的catch
方法上挂起无限时间。即使明确指定了超时! MSDN文档文档不包含任何可以忽略超时并在无限时间内阻止的情况。
这里可能是什么问题?