我在我的項目中使用異步套接字。.net套接字ObjectDisposed異常
當我在我的類NotifyConnection ObjecDispoded異常出現時調用Disconnect方法。 我意識到,這發生becaouse socket.Close()方法調用Dispose裏面。
有沒有人知道socket在這種情況下有多接近?
public void Disconnect()
{
try
{
lock (_syncRoot)
{
_clientSocket.Shutdown(SocketShutdown.Both);
_clientSocket.Close();
}
}
catch (SocketException ex)
{
OnSocketExeceptionThrowed(new EventArgs<SocketException>(ex));
NotificationAgentEm.LogExceptionToConsole(ex);
}
}
我expcect什麼EndReceive不叫,因爲socket.ShutDown關閉套接字接收data..but EndReceive socket.ShutDown後調用; socket.Close。
由於此時不存在套接字,因此拋出了結束異常。
private void OnReceiveData(IAsyncResult ar)
{
try
{
TransferStateObject state = null;
lock(_syncRoot)
{
string message;
state = (TransferStateObject)ar.AsyncState;
// in this place exception throwed . client socket not exist becaouse it destroyed in disconnect method
int bytesRead = _clientSocket.EndReceive(ar);
keleton我如何使用異步套接字。
public void Connect(string host, int port)
{
if (host == null)
throw new NullReferenceException();
try
{
_clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
_clientSocket.Connect(host, port);
}
catch (Exception ex)
{
NotificationAgentEm.LogExceptionToConsole(ex);
throw;
}
}
public void Disconnect()
{
try
{
lock (_syncRoot)
{
_clientSocket.Shutdown(SocketShutdown.Both);
_clientSocket.Close();
}
}
catch (SocketException ex)
{
OnSocketExeceptionThrowed(new EventArgs<SocketException>(ex));
NotificationAgentEm.LogExceptionToConsole(ex);
}
}
public void StartListen()
{
if (_clientSocket == null)
{
throw new InvalidOperationException("No connection");
}
try
{
BeginReceive();
}
catch (SocketException ex)
{
NotificationAgentEm.LogExceptionToConsole(ex);
OnSocketExeceptionThrowed(new EventArgs<SocketException>(ex));
}
}
private void BeginReceive()
{
try
{
var receivedTranferObject = new TransferStateObject();
_clientSocket.BeginReceive(
receivedTranferObject.Buffer,
0,
TransferStateObject.BufferSize,
0,
new AsyncCallback(OnReceiveData),
receivedTranferObject);
}
catch(SocketException ex)
{
OnSocketExeceptionThrowed(new EventArgs<SocketException>(ex));
NotificationAgentEm.LogExceptionToConsole(ex);
}
}
private void OnReceiveData(IAsyncResult ar)
{
try
{
TransferStateObject state = null;
lock(_syncRoot)
{
string message;
state = (TransferStateObject)ar.AsyncState;
// in this place exception throwed . client socket not exist becaouse it destroyed in disconnect method
int bytesRead = _clientSocket.EndReceive(ar);
//bla bla bla
}
}
P.S對不起,我的英語無論我的評論上述我會重組Disconnect方法的
您不必關閉連接,一旦它的處置據我所知。 – CodingBarfield 2011-04-19 08:20:30
很難說出問題出在哪裏,你需要給我們更多關於'主循環'的細節 – 2011-04-19 08:22:22
如果你認爲Disconnect在接收數據的同時被調用,那麼檢查你的程序邏輯。您也可以在Disconnect中設置一個斷點,並查看來電的來源。 – 2011-04-19 08:34:25