Search code examples
c#classindexofsystem.timers.timer

Get Index of an Item in a List of Class Items with Timer Member


I am trying to find the index of the Triggered Timer.

I created a list of Class Entry here in Program.cs

static public List<Entry> Table = new List<Entry>();

This is the class called "Entry" with its constructors in Entry.cs

public class Entry
    {
        public int pktID;

        public Timer pktTimer= new Timer();
    }


public Entry()
      {
      }




public Entry(int _pktID, Boolean idleTimeOutStart)
        {
            this.pktID = _pktID;

            if (idleTimeOutStart == true)
            {
                pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());

                pktTimer.Interval = 10000; // 10000 ms is 10 seconds
                pktTimer.Start();

            }


        }

static void CallDeleteEntry(object sender, System.Timers.ElapsedEventArgs e, int pktIndex)
        {
            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
        }

The items in the list are created randomly. Now each Timer in the List (List Index) will start and then after 10000 msecs, CallDeleteEntry shall be called.

What I need to do is the pass the Index of the Timer when it elapses 10000msec to CallDeleteEntry, so it can remove that item row for the list.

I think something must be modified here to make it work.

idleTimeOutTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());

The List will look like this

ListIndex | Entry Item

0 | pkt | pktTimer

1 | pkt | pktTimer

2 | pkt | pktTimer

3 | pkt | pktTimer

4 | pkt | pktTimer


Solution

  • Your pretty close IndexOf requires the item you're trying to get the index of. in this case the Entry class you're trying to get the index of. I believe in your case it would be the key word this, so IndexOf(this).

    https://msdn.microsoft.com/en-us/library/8bd0tetb(v=vs.110).aspx