Call a single time method within an Event Handler that is called several times?

Asked

Viewed 386 times

2

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

Example:

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

    helloWord();
};

Meaning I want to call the method helloWord() once

  • 2

    It would be interesting for you to improve this control, maybe avoid so many calls or track each call to a different event if possible. If not, you can create a bool to control if the event there was called.

  • @Gabriel Weber I tried to use a 'bool' to make the control and also tried to use 'lock', unfortunately neither of the two worked, this 'Event Handler' discovers services of a device Bluetooth Low Energy, and are about 9 services, so he is called at least 9 times.

3 answers

2


You can give a unsubscribe in the event after it runs for the first time.

Something like:

EventHandler meuEventHandler = null;
meuEventHandler = (object sender, MeuEventArgs e) =>
{    
    helloWord();
    c.Click -= meuEventHandler;
};
c.Click += meuEventHandler;
  • 1

    That solved the problem Vinicius, thank you very much for the answer

1

If you want a more generic solution, using Closures together with the solution of jbueno, here you are:

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 working, here you are.

0

The right thing would be to avoid these "extra" calls. Without more details it is impossible to tell you with certainty what should be done, but in accordance with 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;
    }
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.