C # ArgumentOutOfRangeException when closing forms

I am writing a WinForms C # program.

I'm trying to close all the forms, but my main form FrmMain.

I have to hide my basic form.

I created this by opening two forms. One with my main form and one with the other form shown using the method ShowDialog().

When this code runs on my machine, it seems like it should close all forms correctly. For some reason, when I don't set breakpoints and run this particular piece of code, I get ArgumentOutOfRangeExceptionit because the variable igets to the point where it is -1. When I set breakpoints and walk slowly through each piece of code, it works great.

It makes no sense for the for loop to go all the way for ito get to -1, because I have a condition i >= 0.

Can someone explain to me why the index igets in -1when I don't use breakpoints, but gets in 0when I use breakpoints and every step of every loop cycle?

What can be done to fix this?

Thanks in advance.

            for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
            {
                if (Application.OpenForms[i] is FrmMain)
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i]?.Hide();
                    });
                }
                else
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i]?.Dispose();
                    });
                }
            }

EDIT:

The way I prevented getting an ArgumentOutOfRangeException is to add another variable inside the for loop. This is the code I changed.

            for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
            {
                int i1 = i;
                if (Application.OpenForms[i] is FrmMain)
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i1]?.Hide();
                    });
                }
                else
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i1]?.Dispose();
                    });
                }
            }
+4
source share
1 answer

, for , , i -1 . , .

, BeginInvoke, ( , ), i - , i be -1, Dispose().

, , , , , .

: "" .NET?

+1

Source: https://habr.com/ru/post/1681049/


All Articles