Demo entry 5862471

test

   

Submitted by anonymous on Aug 06, 2016 at 00:03
Language: C#. Code size: 1.8 kB.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Events
{
    class Program
    {
        static void Main(string[] args)
        {
            Alarm alarm = new Alarm(10);
            //Subscribe to event
            alarm.Tick_Event += new Alarm.AlarmTick_Handler(Alarm_Tick_Handler);
            alarm.Run_Timer();
            Console.ReadLine();
        }

        public static void Alarm_Tick_Handler(object sender, string arg)
        {
            Console.WriteLine("Alarm Ringing!!");
            Console.WriteLine("Object: " + sender.ToString());
            Console.WriteLine("EventArgs: " + arg.ToString());
        }
    }

    #region Alarm Class
    public class Alarm
    {
        public delegate void AlarmTick_Handler(object sender, string arg);
        public event AlarmTick_Handler Tick_Event;
        private int Tick;
        private string Event_arg = "This is an argument";

        public Alarm(int tick)
        {
            Tick = tick;
        }

        protected virtual void OnAlarmTick(string arg)
        {
            if(Tick_Event!=null)
            {
                Tick_Event(this,arg);
            }
            else
            {
                //No one is subscribed
                //Do nothing
                Console.WriteLine("No one is subscribed");
            }
        }

        public void Run_Timer()
        {
            for (int i = 0; i <= Tick; i++)
            {
                Console.WriteLine("-->Tick: "+i.ToString());
                Thread.Sleep(50);
            }
            //Fire Event
            OnAlarmTick(this.Event_arg);
        }
    }
    #endregion
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).