This list box will contain the name of processes that are currently running. My function to update the list first checks to see if it does not contain the name of a process that is running, then adds the process if it needs to. Then it checks to see if it contains a process that is no longer running, and then it will remove the process.
Here is the code:
private static void UpdateProcessList(ListBox PC_ProcessList)
{
while (true)
{
if (PC_ProcessList.IsHandleCreated)
{
PC_ProcessList.Invoke(new ThreadStart(
delegate
{
foreach (Process RunningProcess in Process.GetProcesses())
{
if (!PC_ProcessList.Items.Contains(RunningProcess.ProcessName))
{
PC_ProcessList.Items.Add(RunningProcess.ProcessName);
}
}
foreach (object ListedProcess in PC_ProcessList.Items)
{
if (ReturnProcessInstance(Process.GetProcessesByName(ListedProcess.ToString())) == null)
{
try
{
PC_ProcessList.SelectedIndex = PC_ProcessList.SelectedIndex - 1;
}
catch (ArgumentOutOfRangeException)
{
PC_ProcessList.SelectedIndex = PC_ProcessList.SelectedIndex + 1;
}
PC_ProcessList.Items.Remove(ListedProcess);
}
}
}));
}
Thread.Sleep(500);
}
}
It's throwing an InvalidOperationException when I remove a process from the list. It says "List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change." And it highlights line 18. Doesn't that mean that the list is modified by something else other than the current foreach block?
I tried to work around it by making two lists of strings and put the names to be added and names to be removed into them, THEN updating the list after both foreach blocks run but it still gave me the InvalidOperationException. I don't think I understand this exception correctly. ;)