0

我正在尝试查找触发计时器的索引。

我在 Program.cs 中创建了一个类条目列表

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

这是名为“Entry”的类,其构造函数位于 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
        }

列表中的项目是随机创建的。现在列表(列表索引)中的每个计时器都将启动,然后在 10000 毫秒后,将调用 CallDeleteEntry。

我需要做的是在计时器经过 10000 毫秒时将其索引传递给 CallDeleteEntry,这样它就可以删除列表的该项目行。

我认为必须在此处修改某些内容才能使其正常工作。

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

列表将如下所示

列表索引 | 条目

0 | 包| pkt定时器

1 | 包| pkt定时器

2 | 包| pkt定时器

3 | 包| pkt定时器

4 | 包| pkt定时器

4

2 回答 2

1

您非常接近 IndexOf 需要您尝试获取索引的项目。在这种情况下,您尝试获取其索引的 Entry 类。我相信在你的情况下,这将是关键词,所以 IndexOf(this)。

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

于 2017-07-08T01:27:01.857 回答
0

@Jason Mastnick

我在给您的评论中提到的上述错误的原因是

            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry

我应该先停止计时器,然后删除数据包

            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index

顺便说一句,您的解决方案有效。我应该这样写。

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

但是,出现问题。我尝试按顺序添加列表中的条目。传递的第一个 pktIndex 是“1”而不是“0”。由于第一个项目是在索引 0 处添加的。它应该是在此顺序方案中首先删除的项目。一切正常,预计索引 0 处的第一项不会被删除。有任何想法吗?

于 2017-07-08T02:40:37.597 回答