Calling a method once inside an event handler that is called several times?

2

I would like to know how I can ensure that a method is called once inside a Event Handler C #, whereas this Event is called several times.

Example:

//meuEventHandler é chamado várias vezes.
meuEventHandler = (object sender, MeuEventArgs e) =>
{

    helloWord();
};

That is, I want to call the helloWord () method only once

    
asked by anonymous 24.01.2017 / 14:24

3 answers

2

You can give unsubscribe to the event after it is run for the first time.

Something like:

EventHandler meuEventHandler = null;
meuEventHandler = (object sender, MeuEventArgs e) =>
{    
    helloWord();
    c.Click -= meuEventHandler;
};
c.Click += meuEventHandler;
    
24.01.2017 / 15:56
1

If you'd like a more generic solution, using Closures next to the jbueno solution, here it is: / p>

using System;

public class Program
{
    public static void Main()
    {
        EventHandler @event = EventHandlerHelper.Once((object sender, EventArgs e) =>
        {
            Console.WriteLine("Somente uma vez");
        });

        @event.Invoke(null, null);
        @event.Invoke(null, null);
    }
}

public static class Functional
{
    public static Action<T1, T2> Once<T1, T2>(Action<T1, T2> action)
    {
        var executed = false;

        return (T1 arg1, T2 arg2) => {
            if (!executed)
            {
                action(arg1, arg2);
                executed = true;
            }
        };
    }
}

public static class EventHandlerHelper
{
    public static EventHandler Once(Action<object, EventArgs> action)
    {
        return Functional.Once(action).Invoke;
    }
}

To see it working, here is .

    
24.01.2017 / 16:29
0

The right thing to do is avoid these so-called "extras". Without more details it is impossible to tell you with certainty what should be done, but, according to your request. Just create a variable in the class scope to control it.

private bool HelloWorldExecutado = false;

meuEventHandler = (object sender, MeuEventArgs e) =>
{
    if(!HelloWorldExecutado)
    {
        helloWord();
        HelloWorldExecutado = true;
    }
};
    
24.01.2017 / 14:48