Saltar al contenido

System.ObjectDisposedException: no se puede acceder a un objeto desechado. ejemplo de código

Luego de indagar en diversos repositorios y sitios de internet al final nos hemos encontrado la resolución que te compartimos ahora.

Ejemplo: system.objectdisposedexception: no se puede acceder a un objeto desechado. nombre del objeto:

Srv_LoginChannelFactory.Close()iswhereit's being disposed. When you call close you are giving up whatever unmanaged resource you had. Attempting to do something other then inspecting its state or re-opening it results in the "Cannot access a disposed object" exception.

This istrue whenever you close a disposable objectandtryanddo something with it afterwards. For example writing to a file that's closed,or executing a sql statement on a closed database connection.

To address this you have three options.

Don't make the Srv_LoginChannelFactory a field. Instead make it local to the button click. If thisisthe only place you are using it,this probably makes sense to do because it shortens the amount of time you are using an unmanagedresource.

Implement IDisposable (you are supposed dothis whenever you have field that isDisposable) don't close Srv_LoginChannelFactory except in Login.Dispose.

Change the button click to check the State of Srv_LoginChannelFactory before you tryand create a channel with it. You still need to implement IDisposable incase the button click doesn't happen.

Note: EnsureOpened looks like it could be used to check the state, but it only works before its opened. Once its been closed it will throw.RegardingClose() being the same asDispose.

From the section 'Customizing a Dispose Method Name' in Implementing Finalize and Dispose to Clean Up Unmanaged Resources in the Design Guidelines for Developing Class Libraries

Occasionally a domain-specific name ismore appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In thiscase, implement Dispose privately and create a public Close method that calls Dispose. The following code example illustrates this pattern. You can replace Close with a method name appropriate to your domain. This example requires the System namespace.

The idea here isto give parity to the Open method. Personally I think it causes a lot of confusion, but I can't think of anything better (CloseAndDispose?)

valoraciones y comentarios

Si tienes algún pregunta y forma de reaccionar nuestro reseña te recomendamos realizar un paráfrasis y con placer lo interpretaremos.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *