Click here to Skip to main content
15,883,796 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:

I have a list of Socket object. Sometimes due to network issue one of the socket get disposed and when I try to access the list I get the error Can Not access disposed object.

How can I remove disposed object from the list?
Posted
Comments
Sergey Alexandrovich Kryukov 28-Aug-14 2:02am    
Of course you cannot use disposed object. But this is not a good question: you did not provide any essential detail. What list? Anyway, all list objects have methods like Remove, RemoveAt. Use it.
—SA

Many classes which implement IDisposable also offer events: Disposing / Disposed. If the classes you use here do not provide them, override their Dispose method and add such an event.
Then register the event, and remove the item from the lis when the event was raised.
 
Share this answer
 
Try using Dictionary<Endpoint, Socket> instead of List<socket>.
Then, we have a socket list like this:

C#
Dictionary<EndPoint, Socket> activeSocketList = new Dictionary<EndPoint, Socket>();


We can also Add or Remove entity as using the List:

C#
Socket socket = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.IP);
EndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.0.27"), 8080);
socket.Bind(ep);

activeSocketList.Add(socket.LocalEndPoint, socket);
socket.Close();
activeSocketList.Remove(ep);


Also we can use socket.RemoteEndPoint as the Key for "activeSocketList" after socket has connected.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900