Reputation: 25
I've got some kind of a timer. When the time goes out i want to invoke an event. But i don't know how to add a method to the event when i'm making an instance. This is the code :
public delegate void DaysPassed(Action action);
public class TimeAwait
{
public uint DaysLeft;
public event DaysPassed Done;
public TimeAwait(uint daysToWait, Action action)
{
DaysLeft = daysToWait;
Done += action;
}
Upvotes: 0
Views: 70
Reputation: 35790
You don't need event and delegates here. Just invoke your action in the right place. For example:
public class TimeAwait
{
public uint DaysLeft;
private Action action;
private System.Timers.Timer aTimer;
public TimeAwait(uint daysToWait, Action a)
{
action = a;
DaysLeft = daysToWait;
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = daysToWait;
aTimer.Enabled = true;
}
public void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
action.Invoke();
aTimer.Stop();
}
}
class Program
{
static void Main(string[] args)
{
try
{
Action someAction;
someAction = () => Console.WriteLine(DateTime.Now);
var item1 = new TimeAwait(2000, someAction);
var item2 = new TimeAwait(4000, someAction);
Console.ReadKey();
}
catch
{
}
}
}
Upvotes: 1
Reputation: 725
A class like this should do the trick if you just want it to be able to invoke a passed Action. If you want to be able to register other listeners besides the creator you need Events and i wouldn't pass the eventhandlers in a constructor in that case.
public class Countdown
{
int _count;
Action _onZero;
public Countdown(int startValue, Action onZero)
{
_count = startValue;
_onZero = onZero;
}
public void Tick()
{
if(_count == 0)
return; //or throw exception
_count--;
if(_count == 0)
_onZero();
}
}
Upvotes: 0