如何将sender参数传递给.NET中的system.timers.timer
?
timer1[timer] = new System.Timers.Timer(interval);
timer1[timer].AutoReset = true;
timer1[timer].Elapsed += new ElapsedEventHandler(datatransferEvent);
timer1[timer].Start();
GC.KeepAlive(timer1[timer]);
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
serverreconnected.Stop();
reconnect(_opcServer);
}
finally
{
serverreconnected.Start();
}
}
示例:
System.Threading.Timer timer1;
timer1= new System.Threading.Timer(databaseTrensfer, row, dueTime, interval);
public void databaseTrensfer(object row)
{
DataRow rowE = (DataRow)row;
}
行传递给函数databaseTrensfer()
我想将sender参数传递给事件。
提前致谢。
答案 0 :(得分:10)
我喜欢zabulus的方法,但还有另一种选择。创建自己的Timer类,它继承自System.Timers.Timer,它可以保存你想要的任何东西。我选择了基本对象Tag属性,因此可以在其他项目中重复使用。
public class MyTimer : System.Timers.Timer
{
public MyTimer(double interval)
: base(interval)
{
}
public object Tag { get; set; }
}
MyTimer timer;
void test(object sender)
{
timer = new MyTimer(1);
timer.Tag = sender;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MyTimer timer = (MyTimer)sender;
object tag = timer.Tag;
// do whatever you want with tag
}
然后拨打test(with whatever value you want to pass)
。
答案 1 :(得分:1)
创建保存行的聚合类。
class RowHolderEventArgs : EventArgs
{
public DataRow row;
public RowHolderEventArgs(DataRow row)
{
this.row = row;
}
};
public delegate void RowHolderEvent(object sender, RowHolderEventArgs e);
class RowHolder
{
public event RowHolderEvent Elapsed;
DataRow row;
public RowHolder(DataRow row, Timer timer)
{
this.row = row;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (this.Elapsed != null)
{
Elapsed(sender, new RowHolderEventArgs(row));
}
}
}
使用
timer1[timer] = new System.Timers.Timer(interval);
rowHolder[timer] = new RowHolder(timer1[timer],row[timer]);
rowHolder.Elapsed+=new RowHolderEvent(databaseTrensfer)
public void databaseTrensfer(object sender, HolderEventArgs e)
{
DataRow rowE = (DataRow)e.row;
}
答案 2 :(得分:1)
如下:
static Timer timer;
static void Main(string[] args)
{
var row = default(DataRow); // Some row
timer = new Timer(30000);
timer.Elapsed += (_, __) => databaseTrensfer(row);
}
static void databaseTrensfer(DataRow row)
{
// Do something with 'row'
}