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.
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.– rLinhares
@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.
– Alisson Manfron