tags:

views:

109

answers:

2

I want some code to be triggered every second. Usually, I'd create a Timer and link to its event. I wondered if there is a better way. Maybe without the requirement to implement IDisposable.

Edit: My main concern is LoC. I don't feel like writing an entire class when something along the lines of this could work, too:

System.RegisterPeriodicEvent (1000, () => { Syso("asdf"); };

In my dreams this event is automatically unregistered as soon as the current threat terminates.

I get the feeling that I should just write a class which implements the above method.

+1  A: 

If it ain't broke, don't try to fix it.

Running x piece of code every y amount of time is what a timer does, and it does it very well.

As for avoiding IDisposable, not really, not without creating memory leaks anyway. The only two ways I can think of to do this is with kernel primitive timers (which need to be released, IDisposable), or with a thread and Thread.Sleep() or similar (and then you need to kill the thread when you're done, again IDisposable).

Matthew Scharley
A: 

This isn't exactly a lightweight way of doing things, but Retlang has very nice timer functionality. In particular, it deals up front with nasty threading issues (by serializing the calls) and allows you to interleave event driven work with timers.

Best of all, you dispose of the fiber and you dispose of the event. It's not trivial though: you've got to design your code around the API (which later on you'll regard as worth it, but at first looks like a pain in the neck).

Julian Birch