Search code examples
c#objectdisposedexception

ObjectDisposedException but why and what is disposed?


So as the title says I don't know why there is this "ObejectDisposedException". It is occuring when the download has finished during the last Call of "OnDownloadUpdated(..)".

The line "this.Invoke(..)" throws the exception.

    ChromiumWebBrowser browser;

    public frmRocketPluginDownload()
    {
        InitializeComponent();

        var settings = new CefSettings();
        settings.BrowserSubprocessPath = @"x86\CefSharp.BrowserSubprocess.exe";


        Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);

        browser = new ChromiumWebBrowser("");
        browser.Dock = DockStyle.Fill;
        browser.AddressChanged += Browser_AddressChanged;
        browser.DownloadHandler = this;


        panelBody.Controls.Add(browser);
    }


    public void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
    {
        this.Invoke((MethodInvoker)delegate
        {
            if (downloadItem.PercentComplete == 100)
            {
                this.Show();
            }
        });
    }

Solution

  • It is race condition. When Form is closing during OnDownloadUpdated (which I assume is called from other thread) then is up to which operation ends first: Form disposing or OnDownloadUpdated. To prevent this check in Form.Closing event if your method has ended, otherwise set Closing.Cancel to true to prevent closing the Form.