Search code examples
c#.net-coretimerevent-handling

C# Determine which of several timers has expired


I have an array of objects and each object has its own timer. If, when constructing the arrayed objects I pass my own timer event handler for use in the timers, is there any way to tell which object's timer has expired.

If not, it seems all the objects in my array would need to catch their own timers and I'd need to implement a completely different delegate that took something like InnerObject as a parameter so the inner objects own event handler could call it like this: OuterDelegate(this,eventArgs);

All the various ways along the same line are such a ridiculous amount of trouble I can't help but think there must be a better way. On other systems the timer always takes a token that is included in parameters to the event handler but I can't find anything resembling that in .net (core).


Solution

  • Well it turns out that System.Timers is complete junk but not your only choice. System.Threading.Timer has exactly the features I was looking for. I just didn't realize there were two version until I stumbled on certain complaints that clued me to the fact that they are not the same and I finally looked at the threading version.

    Edit:

    System.Threading.Timer's callback looks like this

    public delegate void TimerCallback(object state);
    

    Where state is an arbitrary object passed to the timer during construction. It can encapsulate anything the event handler needs to properly handle the specific instance of the event. You can even set properties or call methods on the object during event handling thus controlling its state based on the timer.

    Edit-2

    The only thing in the System.Timers implementation that is vaguely similar is the ability to attach a System.ComponentModel.ComponentCollection and the ability to point to a Component within the collection. These are COM objects belonging to System.​Windows.​Forms.​Control. Even if you extend the class to meet your own needs you drag support for unusable properties around with you.

    You can extend the System.Threading.Timer just as easily without dragging unnecessary baggage along.