how to raise event with timer?

三世轮回 提交于 2019-12-06 09:48:31

First, I would make a base class that has handles the logic relating to the event. Here is an example:

/// <summary>
/// Inherit from this class and you will get an event that people can subsribe
/// to plus an easy way to raise that event.
/// </summary>
public abstract class BaseClassThatCanRaiseEvent
{
    /// <summary>
    /// This is a custom EventArgs class that exposes a string value
    /// </summary>
    public class StringEventArgs : EventArgs
    {
        public StringEventArgs(string value)
        {
            Value = value;
        }

        public string Value { get; private set; }
    }

    //The event itself that people can subscribe to
    public event EventHandler<StringEventArgs> NewStringAvailable;

    /// <summary>
    /// Helper method that raises the event with the given string
    /// </summary>
    protected void RaiseEvent(string value)
    {
        var e = NewStringAvailable;
        if(e != null)
            e(this, new StringEventArgs(value));
    }
}

That class declares a custom EventArgs class to expose the string value and a helper method for raising the event. Once you update your timers to inherit from that class, you'll be able to do something like:

RaiseEvent(aida.ToString());

You can subscribe to these events like any other event in .Net:

public static void Main()
{
    var timer1 = new FormWithTimer();
    var timer2 = new FormWithTimer2();

    timer1.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable);

    //Same for timer2
}

static void timer1_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e)
{
    var theString = e.Value;

    //To something with 'theString' that came from timer 1
    Console.WriteLine("Just got: " + theString);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!