I have tested multiple ways to close all MDI child forms, but they seem to be unstable. In many cases I'll get ObjectDisposedException
.
What I tried:
'collect copy of app forms array
Dim formsToClose As Form() = My.Application.OpenForms.OfType(Of Form).ToArray()
'iterate over collection, skip special forms
For i As Integer = LBound(formsToClose) + 1 To UBound(formsToClose)
Dim f As Form = formsToClose(i)
If f Is Nothing OrElse frmSpecial.IsMyInstance(f) Then Continue For
Try
clsWinForms.ForceCloseForm(f)
Catch ex As Exception
'some code here
End Try
Next i
ForceCloseForm()
does Form.Close()
after it switched off form validation.
ObjectDisposedException
.f.Disposing
and f.IsDisposed
, there is no improvement.How can I close all open forms in stable way?
(If you want to give some code excerpt, you can choose C# or VB.NET.)
I have found the issue. Form calling CloseAllForms()
was attempting to operate its controls after closing of all forms (including itself) was finished. Checking Disposing Or IsDisposed
expression helped to avoid the problem.
I'm staying with closing approach shown by Microsoft, i.e. instead of creating copy of forms collection, iterate on live collection and increase index only if some form has to be excluded from closing (or is invalid).
On the other hand I believe that other approaches mentioned in the question are nearly equivalent. As I found out, problem was elsewhere.