I building a service application in c#. i’m trying to make my action (array) with timer every 2 second. but my timer keep die after my function call finished.
my Onstart:
...
Alaram Fi = new Alaram();
Fi.AgentStart();
GC.KeepAlive(Fi);
...
My Alaram class:
public void AgentStart()
{
...
int i = 0;
Timer[] timers = new Timer[count];
while (myReader.Read())
{
timers[i] = new Timer(coba, myReader["DeviceId"], 0, 2000);
i++;
}
GC.KeepAlive(timers);
}
My Action:
public void coba(object id)
{
...
int sec = Convert.ToInt32((string)myCommand.ExecuteScalar());
sec++;
myCommand = new SqlCommand("UPDATE Roles SET Value ='" + sec.ToString() + "' WHERE Name = 'Fire" + id.ToString() + "'", ibmsConnect);
myCommand.ExecuteNonQuery();
...
}
my timer only execute maximum 36 times after that my timer didn’t execute anymore. I need it to keep live until the service is stop
anyone have idea why my timer keep stoping tick??
GC.KeepAlivewill only prevent aggressive garbage collecting on the timers for the scope in which they are declared (or stored), which would be the array in theAgentStartmethod. Once the array and the timers go out of scope (when the method is done executing) they will begin to be collected by garbage collection.You will need to declare the array in a location where it will stay in scope. One way to do this is by marking the array as static and placing it on the class level . Next instantiate the timers you assign to the array in a static constructor of the class. This should keep them alive.