This project has moved. For the latest updates, please go here.
2
Vote

System.InvalidOperationException: Collection was modified; enumeration operation may not execute

description

Setup: Windows 10 x64 Pro (with AU), build 1607. VS2015. Downloaded & upgraded
AutoUpdater.NET source code to Framework v4 due to the project I'm working on.

When using this in a WinForms environment, I was receiving:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
at System.Windows.Forms.Application.ExitInternal()
at System.Windows.Forms.Application.Exit(CancelEventArgs e)
at AutoUpdaterDotNET.DownloadUpdateDialog.OnDownloadComplete(Object sender, AsyncCompletedEventArgs e)
at System.Net.WebClient.OnDownloadFileCompleted(AsyncCompletedEventArgs e)
at System.Net.WebClient.DownloadFileOperationCompleted(Object arg)


In the DownloadUpdateDialog class, there is the following code:
    private void OnDownloadComplete(object sender, AsyncCompletedEventArgs e)
    {
        if (!e.Cancelled)
        {
            var processStartInfo = new ProcessStartInfo {FileName = _tempPath, UseShellExecute = true};
            Process.Start(processStartInfo);

            var currentProcess = Process.GetCurrentProcess();

            foreach (var process in Process.GetProcessesByName(currentProcess.ProcessName))
            {
                if (process.Id != currentProcess.Id)
                {
                    process.Kill();
                }
            }

            if (AutoUpdater.IsWinFormsApplication)
            {
                Application.Exit();
            }
            else
            {
                Environment.Exit(0);
            }
        }
    }

To get this to work, I simply had to change lines:
            if (AutoUpdater.IsWinFormsApplication)
            {
                Application.Exit();
            }
            else
            {
                Environment.Exit(0);
            }

to just:
            Environment.Exit(0);

Application.Exit() would have been the correct or more preferred way to terminate the WinForms app, but for some reason was causing my exception. Hopefully this might help the developer and others!

comments