you can pass a reference to the System.Threading.Timer object to your callback function, something like this:
System.Threading.Timer myTimer = new System.Threading.Timer(new TimerCallback(DoSomething), myTimer, 2000, Timeout.Infinite);
Because in the "DoSomething" method, I want to call:
myTimer.Change(5000, Timeout.Infinite);
I will attach the draft console application below. The idea is this: I have a list of timers. And each timer makes some kind of request, and when it receives it, it changes some general data. But I canβt pass the timer link into my callback and I canβt use it in the index, because for some reason (investigation) it becomes β-1β.
using System;
using System.Collections.Generic;
using System.Threading;
namespace TimersInThreads
{
class Program
{
public static int sharedDataInt;
static private readonly object lockObject = new object();
public static List<System.Threading.Timer> timers = new List<Timer>();
static void Main(string[] args)
{
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(DoSomething), timers.Count - 1, 2000, Timeout.Infinite);
timers.Add(timer);
System.Threading.Timer timer2 = new System.Threading.Timer(new TimerCallback(DoSomething), timers.Count - 1, 2000, Timeout.Infinite);
timers.Add(timer2);
System.Threading.Timer timer3 = new System.Threading.Timer(new TimerCallback(DoSomething), timers.Count - 1, 2000, Timeout.Infinite);
timers.Add(timer3);
Console.ReadLine();
}
static void DoSomething(object timerIndex)
{
var x = getSomeNumberWithDelay();
lock (lockObject)
{
sharedDataInt++;
Console.WriteLine("Timer" + (int)timerIndex + ", SHaredDataInt: " + sharedDataInt + "\t\t" + DateTime.Now.ToString("HH:mm:ss tt") + "." + DateTime.Now.Millisecond.ToString());
}
timers[(int)timerIndex].Change(5000, Timeout.Infinite);
}
static int getSomeNumberWithDelay()
{
Thread.Sleep(5000);
return 3;
}
}
}
Please give me some idea or advice. Thank you very much!
source
share