将额外参数传递给事件处理程序?

时间:2015-07-24 13:15:21

标签: c# events

我正在尝试将一些数据从一个事件处理程序传递到另一个事件处理程序,但我有点卡住了。 在以下代码中,我有两个事件:

  • 一个是"计时器已经过去"事件
  • 第二个是" Ping已完成"从"计时器中提取的事件已经过去"事件

在" Ping完成" event,我需要从timer elapsed事件中访问一个变量。我怎么能这样做?

void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
   for (int i = 0; i < this.View.Rows.Count; i++)
   {
      this.IP = View.Rows[i].Cells[2].Value.ToString();
      PingOptions Options = new PingOptions(10, true);
      Ping thisPing = new Ping();
      thisPing.SendAsync(IPAddress.Parse(IP), 100, new byte[0], Options);
      thisPing.PingCompleted += new PingCompletedEventHandler(thisPing_PingCompleted);                    
    }
}

void thisPing_PingCompleted(object sender, PingCompletedEventArgs e)
{
    //i need to accsess the "int i" of the above loop Here
}

2 个答案:

答案 0 :(得分:3)

这正是SendAsync方法的userToken参数应该用于

PingOptions options = new PingOptions(10, true);
Ping thisPing = new Ping();
thisPing.SendAsync(IPAddress.Parse(IP), 100, new byte[0], options, i);
thisPing.PingCompleted += new PingCompletedEventHandler(thisPing_PingCompleted); 
...

void thisPing_PingCompleted(object sender, PingCompletedEventArgs e)
{
    var index = (int)e.UserState;
    ...
}

另外,假设您使用SendAsync,则每次迭代不需要创建Ping的实例。您可以简单地重用现有实例,每次调用SendAsync都会在不同的线程中发送ping,然后回调给您的事件处理程序,即

void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{            
    PingOptions Options = new PingOptions(10, true);
    Ping thisPing = new Ping();
    thisPing.PingCompleted += new PingCompletedEventHandler(thisPing_PingCompleted);  
    // send pings asynchronously
    for (int i = 0; i < this.View.Rows.Count; i++)
    {
        var ip = View.Rows[i].Cells[2].Value.ToString();
        thisPing.SendAsync(ip, 100, new byte[0], options, i);                  
    }
}

答案 1 :(得分:1)

您可以从Ping派生,然后在Pings构造函数中传递您的参数。然后你可以自由地改变事件的行为,你可以根据自己的需要改变它。

我做了一个简单的课程,你可以从

开始
class ExtendedPing : Ping
{
    public delegate void ExtendedPing_Completed(object sender, PingCompletedEventArgs e, int identifier);
    public event ExtendedPing_Completed On_ExtendedPing_Completed;

    private int _i = 0;

    public ExtendedPing(int i)
    {
        _i = i;
        base.PingCompleted += ExtendedPing_PingCompleted;
    }

    void ExtendedPing_PingCompleted(object sender, PingCompletedEventArgs e)
    {
        if (On_ExtendedPing_Completed != null) 
        {
            On_ExtendedPing_Completed(sender, e, _i);
        }
    }
}

随意阅读https://github.com/monde-sistemas/delphi-aws-ses更多关于遗产的内容。