I am not sure if it is the only or best solution, but the following code achieves what I was looking to do. Basically, all I have done is changed the "dumb" integer _count variable to a class, which means it is passed by reference and it can maintain its own internal state, like this:
using System;
using System.Threading;
namespace ConsoleApplication1
{
public class Repeater
{
public Repeater( Action<object> callback, object state )
{
TimerCallback tcb = ( s ) => callback( s );
_timer = new Timer( tcb, state, 0, 5000 );
}
private Timer _timer = null;
}
public class Counter
{
public int Count { get; set; }
}
public class Program
{
static void Main( string[] args )
{
Counter counter = new Counter();
Action<object> callback = MyFunction;
Repeater repeater = new Repeater( callback, counter );
Console.ReadKey();
}
private static void MyFunction( object state )
{
Counter counter = state as Counter;
Console.WriteLine( $"event...{counter.Count}" );
counter.Count = counter.Count + 1;
}
}
}
This seems to work. I would still appreciate any comments though.