如何从列表中删除已处置的对象? [英] How can I remove disposed object from the list?

查看:78
本文介绍了如何从列表中删除已处置的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个Socket对象列表。有时由于网络问题,其中一个套接字被丢弃,当我尝试访问列表时,我得到错误无法访问已处置对象。



如何从列表中删除已处置的对象?

解决方案

许多实现IDisposable的类也提供事件:Disposing / Disposed。如果你在这里使用的类没有提供它们,则覆盖它们的Dispose方法并添加这样的事件。

然后注册事件,并在事件被引发时从lis中删除该项。

尝试使用Dictionary< Endpoint,Socket>而不是List< socket>。

然后,我们有一个这样的套接字列表:



 Dictionary< ; EndPoint,Socket> activeSocketList =  new 字典< EndPoint,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);





我们也可以在socket连接后使用socket.RemoteEndPoint作为activeSocketList的密钥。



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?

解决方案

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.


Try using Dictionary<Endpoint, Socket> instead of List<socket>.
Then, we have a socket list like this:

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



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

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.


这篇关于如何从列表中删除已处置的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆