mbrc
mbrc

Reputation: 3973

C# Remove Event Handler after is called or call it just once

_cefGlueBrowser.LoadEnd += (s, e) =>
{
    BeginInvoke(new Action(() =>
    {
         MyCefStringVisitor visitor = new MyCefStringVisitor(this, m_url);
         e.Browser.GetMainFrame().GetSource(visitor);
         loaded = true;
    }));
};

But problem is that Event Handler is called many times. After each JS reload for example. How to remove multiple calls. How to call LoadEnd event just once.

I try with

_cefGlueBrowser.LoadEnd -= delegate { };

but not working.

What can i do? I want to call it just once!

Upvotes: 15

Views: 12358

Answers (4)

Vito De Tullio
Vito De Tullio

Reputation: 1685

Based on Mark Gravel response, I think you need also at least a flag

        bool done = false;
        EventHandler eh = null;
        obj.evt += eh = (_, e) => {
            obj.evt -= eh;
            if (done)
                return;
            done = true;

            // stuff
        };

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064144

EventHandler handler = null;
obj.SomeEvent += handler = (s, e) => {
    obj.SomeEvent -= handler;
    // more stuff
};

This works because it is the variable that us captured (lexical closure), not the value of the variable at any particular time.

Upvotes: 54

Thomas Weller
Thomas Weller

Reputation: 11717

Define the event handler in a separate method and add the unsubscribing operation to its method body:

public EventHandler OnLoadEnd(object sender, <args>)
{
    BeginInvoke(new Action(() =>
                    {
                        MyCefStringVisitor visitor = new MyCefStringVisitor(this, m_url);
                        _cefGlueBrowser.Browser.GetMainFrame().GetSource(visitor);
                        loaded = true;
                    }));

    _cefGlueBrowser.LoadEnd -= OnLoadEnd;
}

Upvotes: 3

Ondrej Janacek
Ondrej Janacek

Reputation: 12636

Create a method

public void Browser_LoadEnd(object sender, EventArgs e)
{
    BeginInvoke(new Action(() =>
    {
         MyCefStringVisitor visitor = new MyCefStringVisitor(this, m_url);
         _cefGlueBrowser.Browser.GetMainFrame().GetSource(visitor);
         loaded = true;
    }));
}

subscribe

_cefGlueBrowser.LoadEnd += Browser_LoadEnd;

and unsubscribe

_cefGlueBrowser.LoadEnd -= Browser_LoadEnd;

Note, I assume that the LoadEnd event takes EventArgs and not some derived class.

Upvotes: 4

Related Questions