如何将参数传递给计时器事件

时间:2019-01-24 00:29:49

标签: c# timer

我正在尝试根据以下代码实现计时器。我想将参数传递给计时器事件。我在下面使用了匿名函数方法。

但是,这只会将第一个参数传递给OnTimerElapsedEvent。有人可以请教吗?

    class Program
{
    static void Main(string[] args)
    {
        ClassA obj = new ClassA();
        Console.WriteLine("Start" + " " + System.DateTime.Now);
        obj.SampleMethod("hello", 3000);
        Thread.Sleep(4000);
        obj.SampleMethod("world", 6000);
        Console.ReadKey();
    }
}

class ClassA
{
    private System.Timers.Timer tTimer;

    public void SampleMethod(string strParam, int iTimerInterval)
    {
        if (tTimer == null)
        {
            tTimer = new System.Timers.Timer();
            tTimer.Elapsed += (sender, e) =>
                OnTimerElapsedEvent(sender, e, strParam);
        }

        tTimer.Interval = iTimerInterval;
        tTimer.Enabled = true;
        tTimer.Start();
    }

    private void OnTimerElapsedEvent(object source, ElapsedEventArgs e, string strParam)
    {
        //use strParam value here
        Console.WriteLine(strParam + " " + System.DateTime.Now);
        if (strParam == "world")
        {
            tTimer.Stop();
            tTimer.Enabled = false;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以继承Timer类,以在构造函数中提供一个参数,如下所示。或者,您可以继承Timer类并提供属性:

 [TestClass]
public class TimerTester
{
    [TestMethod]
    public void TestYourTimer()
    {
        var timer1 = new TimerWithParameter("param1");
        timer1.Interval = 1000;
        timer1.ElapsedEvent += Timer_ElapsedEvent;
        timer1.Start();

        var timer2 = new TimerWithParameter("param2");
        timer2.Interval = 1300;
        timer2.ElapsedEvent += Timer_ElapsedEvent;
        timer2.Start();

        Thread.Sleep(5000);
    }

    private void Timer_ElapsedEvent(object source, ElapsedEventArgs e, string strParam)
    {
        Debug.WriteLine(strParam);
    }
}

public delegate void ElapsedWithParameterDelegate(object source, ElapsedEventArgs e, string strParam);

public class TimerWithParameter:Timer
{
    private readonly string _strParam;
    public event ElapsedWithParameterDelegate ElapsedEvent;

    public TimerWithParameter(string strParam)
    {
        _strParam = strParam;
        this.Elapsed += TimerWithParameter_Elapsed;
    }

    private void TimerWithParameter_Elapsed(object sender, ElapsedEventArgs e)
    {
        ElapsedEvent?.Invoke(this, e, _strParam);
    }
}