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.
- This approach randomly crashes with
ObjectDisposedException
. - Running with index from last to 0 crashes with even higher probability.
- While-loop-based trick from Microsoft (operating on live collection, keeping index constant on success) crashes the same way, too.
- If I insert test for
f.Disposing
andf.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.)