Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Disposing of Objects from a Generic.List(Of ...)

Status
Not open for further replies.

woogoo

Programmer
Feb 14, 2004
247
GB
Hi,

I have an Generic.List(Of MyObjects) these Objects implement IDisposable and as a result I want to clean up on exit.

Regardless of how I attack this I get an error when trying this (or similar):
Code:
Protected Overrides Sub OnStop()
        ' Service is stopping so clean up.
        Dim m_Object As MyObject = Nothing
        For Each m_Object In m_Objects
            m_Objects.Remove(m_Object)
            m_Object.Dispose()
        Next
    End Sub

The error I get is
Code:
Collection was modified; enumeration operation may not execute.
I can only assume that m_Object is only a reference to the actual Instance in the List(Of...). Does anyone know how I can clean up properly?



woogoo
 
Use the for loop to just call the Dispose method. Afterwards, delete or replace the whole list.

+++ Despite being wrong in every important aspect, that is a very good analogy +++
Hex (in Darwin's Watch)
 
That's what I love about this site. I'd worked that out, and was about to update the post only to have a reply; brilliant.

Thanks for your time anyway.

woogoo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top