我使用BeginConnect()编写了一个小的c#类来检查TCP连接(连接到TCP套接字成功)。它似乎运行良好,如果有问题的端点可用且TCP会话实际连接。
然而,当端点没有监听并且连接超时时,会发生一些奇怪的事情:该类保持“挂起”大约15到20秒。这与默认超时值一致。
但是,当超时触发时我调用socket.Close() - MSDN表示取消所有异步操作。
为什么当连接失败时,类会阻止应用程序关闭?我做错了什么?
public class CheckTCP
{
#region "Member Variables"
// socket connect timeout value
private int _timeout = 2000;
// check complete event
public event EventHandler<CheckCompletedEventArgs> CheckCompleted;
// perform TCP connect check
public void PerformCheck(EndPoint Socket)
{
StateObject state = new StateObject();
state.Me = this;
state.WorkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
state.TimeoutTimer = new Timer();
state.TimeoutTimer.Interval = _timeout;
state.TimeoutTimer.Elapsed += (sender, e) => timeout_elapsed(sender, e, state);
state.TimeoutTimer.Start();
state.WorkSocket.SendTimeout = _timeout;
state.WorkSocket.ReceiveTimeout = _timeout;
state.WorkSocket.BeginConnect(Socket, new AsyncCallback(ConnectCallback), state);
}
// connection callback
private static void ConnectCallback(IAsyncResult ar)
{
StateObject state = (StateObject) ar.AsyncState;
state.TimeoutTimer.Stop();
state.TimeoutTimer.Dispose();
CheckCompletedEventArgs ea = new CheckCompletedEventArgs();
if (state.WorkSocket.Connected)
{
state.WorkSocket.EndConnect(ar);
state.WorkSocket.Close();
ea.Success = true;
state.Me.OnCheckCompleted(ea);
}
else
{
ea.Success = false;
state.Me.OnCheckCompleted(ea);
}
state.WorkSocket.Dispose();
state.Me = null;
}
// timeout callback
private void timeout_elapsed(object sender, EventArgs e, StateObject state)
{
state.TimeoutTimer.Stop();
state.WorkSocket.Close();
}
#endregion
// raiseevent helper
protected virtual void OnCheckCompleted(CheckCompletedEventArgs e)
{
// raise the event
EventHandler<CheckCompletedEventArgs> handler = CheckCompleted;
if (handler != null)
{
handler(this, e);
}
}
// checkcompleted event args class
public class CheckCompletedEventArgs : EventArgs
{
public bool Success { set; get; }
}
// async state object
public class StateObject
{
public EndPoint EndpointSocket { set; get; }
public Socket WorkSocket { set; get; }
public Timer TimeoutTimer { set; get; }
public CheckTCP Me { set; get; }
}
}