Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the sender parameter to the system.timers.timer

Tags:

c#

.net

How do you pass the sender parameter to the system.timers.timer in .NET?

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();
    }
}

Example:

System.Threading.Timer timer1;
timer1= new System.Threading.Timer(databaseTrensfer, row, dueTime, interval);

public void databaseTrensfer(object row)
{
    DataRow rowE = (DataRow)row;
}

Row pass to the parameter to the function databaseTrensfer()

I want to pass the the sender parameter to the event.

Thanks in advance.

like image 845
vrushali Avatar asked Jun 16 '11 07:06

vrushali


2 Answers

I like zabulus's method, but there is an alternative. Create your own Timer class that inherits from System.Timers.Timer and it can hold anything you want. I chose to do the basic object Tag property so it can be reused in other projects.

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
}

Then call test(with whatever value you want to pass).

like image 77
Chuck Savage Avatar answered Oct 13 '22 03:10

Chuck Savage


create aggregation class that holds your row.

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));
        }
    }
}

using

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;
}
like image 22
zabulus Avatar answered Oct 13 '22 01:10

zabulus