Why does wpf+c-sharp, loop in a non-debug state when it uses while and loops the selected items with SelectedItems.Count as its condition?

the platform on which the problem occurs

win10 1703 | Visual Studio Community 2017 15.7.4 / 27703.2035 | .NET Framework 4.7.03056 | CSC 2.8.3-beta6-62923-07

related codes

void RemoveFilesListItems(object sender, RoutedEventArgs e)
{
    //FilesListListBoxSelectionModeExtended
    while (FilesList.SelectedItems.Count>0) //
    {
        FilesList.Items.Remove(FilesList.SelectedItems[0]);
    }
}

expected results

use FilesList.Items.Remove (FilesList.SelectedItems [0]); this statement deletes the first selected item. I expect this code to cycle through the deletion of the first item, when SelectedItems.Count > 0 , thus achieving the purpose of batch deletion of the selected item.

results obtained

  • debugging with vs, everything is fine.
  • runs directly after compilation, and everything works fine when multiple item, in ListBox is selected but not all item is selected.
  • runs directly after compilation, and selects all item, in ListBox to execute this method, resulting in an endless loop (really an endless loop, I try to add a statement to write txt in it, and there is a lot of content in the txt after running), and the program loses its response.

guess

will it cause problems with the update of SelectedItems.Count values if the loop is too fast?

desired answer

about the cause of this endless cycle. I have done this in a different way, just curious about the reason for this endless cycle. Please also answer your questions, thank you ~

Mar.30,2021

. Your code is really. I almost went around it

while (FilesList.SelectedItems.Count>0) //
    {
        FilesList.Items.Remove(FilesList.SelectedItem);
    }

while (1 > 0) {} is an endless cycle

.

FilesList.SelectedItems and FilesList.Items are two objects. No wonder they are not dead.

Menu