从委托内的集合中删除项目时出现异常

Exception while removing items from a collection inside a delegate

我有 List<ActiveDeviceProcess> 保留 windows 表格。当我通过 FormClosing 侦听器从另一个表单调用 activeDeviceProcessFormClosed(deviceNumber) 时。我得到一个错误。但我不知道为什么。一切看起来都很好。这是我的方法:

public void activeDeviceProcessFormClosed(int deviceNumber)
{
     this.Invoke((MethodInvoker)delegate
     {
         foreach (ActiveDeviceProcess i in activeDeviceProcessForms)
         {
             if (i.device.deviceNumber == deviceNumber)
             {
                 activeDeviceProcessForms.Remove(i);
             }
         }
     });
}

这里是错误:

An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code

感谢您的帮助!

您不能在迭代集合时从集合中删除项目。使用 List<T>.RemoveAll 代替:

public void activeDeviceProcessFormClosed(int deviceNumber)
{
     this.Invoke((MethodInvoker)delegate
     {
        activeDeviceProcessForms.RemoveAll(i => i.Device.DeviceNumber == deviceNumber);
     });
}

编辑:

如果您只有多个具有相同设备 ID 的项目想要删除第一个具有 DeviceNumber 的元素,您可以使用 Enumerable.FirstOrDefaultList<T>.Remove:

public void activeDeviceProcessFormClosed(int deviceNumber)
{
     this.Invoke((MethodInvoker)delegate
     {
        var device = activeDeviceProcessForms.FirstOrDefault(
                        i => i.Device.DeviceNumber == deviceNumber);

        if (device != null)
            activeDeviceProcessForms.Remove(device);
     });
}

因为它是迭代的,所以当我删除列表中的一个元素时,我应该添加 "break" 命令。

public void activeDeviceProcessFormClosed(int deviceNumber)
{
     this.Invoke((MethodInvoker)delegate
     {
         foreach (ActiveDeviceProcess i in activeDeviceProcessForms)
         {
             if (i.device.deviceNumber == deviceNumber)
             {
                 activeDeviceProcessForms.Remove(i);
                 break;//----> this was added.
             }
         }
     });
}