Home > OS >  Get it's "parent" in side System.Timers.Timer
Get it's "parent" in side System.Timers.Timer

Time:11-11

Well, the title is confusing because I don't know how to express it well, feel free to correct it.

I have a class TaskTimer to access and modify some of it's property, but I don't know how to get it's parent in the elapsed timer event. I do this because whenever i stop a System.Timers.Timer it is still running for the last time. By doing this it will help preventing the timer from misfiring.

    public List<TaskTimer> _taskTimers; 
    public void CreateTask(int _taskID, int _invterval)
    {
        TaskTimer taskTimer = new TaskTimer();
        taskTimer.taskID = _taskID;
        taskTimer.Interval = _invterval;
        taskTimer.Elapsed  = new ElapsedEventHandler(OnTweakTimedEvent_autoTask);
        _taskTimers.Add(taskTimer);
    }
    public class TaskTimer : System.Timers.Timer
    {
        private int taskID { get ; set ;}
    }

Here is a sample of Eslapsed timer event and what i want to do:

    string currentTaskID = "something";
    private void OnTweakTimedEvent_autoTask(object sender, ElapsedEventArgs e)
    {
        if (currentTask == {tell this event to get it's taskID)
        {
            //to do here
        }
    }

I know this question sounds silly, any help is appreciated!

CodePudding user response:

Since you have inherited directly from Timer

public class TaskTimer : System.Timers.Timer

Then the sender parameter should be the TaskTimer. The exception to this is, if you call this method directly and supply null or something else

private void OnTweakTimedEvent_autoTask(object sender, ElapsedEventArgs e)
{
   // safety first
   if(sender is not TaskTimer parent)
      throw new InvalidOperationException("Hmm, Error you must have");
  
   Console.WriteLine(parent.TaskID); 
}
  • Related