M
M
Maxim K2021-10-23 22:10:15
C++ / C#
Maxim K, 2021-10-23 22:10:15

C # - floating glitch - how correct was it?

There is a method:

private void Web_TitleChanged(object sender, TitleChangedEventArgs e)
        {
                Invoke(new Action(() => Text = e.Title));
        }

Rarely, but it happens - the application closes, I used the debugger, because I caught the moment - the debugger displayed in the line Invoke................ - an error: "Access to the liquidated object is impossible".

I found one solution, check for IsDisposed:

I did this:

private void Web_TitleChanged(object sender, TitleChangedEventArgs e)
        {
            if (!IsDisposed)
            {
                Invoke(new Action(() => Text = e.Title));
            }
        }

How well done? It's just that an error may very well not be caught and I would not want to return to this one.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris the Animal, 2021-10-23
@mkvmaks

Subscribe to the FormClosing event (if not already subscribed) and, in its handler, unsubscribe from the TitleChanged, AddressChanged, LoadingStateChanged event handlers:

public partial class BrowserMain : Form
{
    public BrowserMain()
    {
        InitializeComponent();
        
        WebBrowser = new ChromiumWebBrowser(
            string.IsNullOrWhiteSpace(address) ? "about:blank" : address)
        {
            // ...
        };

        Controls.Add(WebBrowser);

        WebBrowser.TitleChanged += WebBrowser_TitleChanged;
        WebBrowser.AddressChanged += WebBrowser_AddressChanged;
        WebBrowser.LoadingStateChanged += webBrowser_DocumentCompleted;
    }

    private void BrowserMain_FormClosing(object sender, FormClosingEventArgs e)
    {
       // После вызова этих строк методы WebBrowser_TitleChanged, WebBrowser_AddressChanged
       // и webBrowser_DocumentCompleted не будут выполняться. 
       // Это и не нужно, так как окно закрывается.
        WebBrowser.TitleChanged -= WebBrowser_TitleChanged;
        WebBrowser.AddressChanged -= WebBrowser_AddressChanged;
        WebBrowser.LoadingStateChanged -= webBrowser_DocumentCompleted;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question