Execute a Method Periodically - CSharp Reflection

CSharp examples for Reflection:Method

Description

Execute a Method Periodically

Demo Code


using System;/*from   w  ww.j av a2  s. c  o  m*/
using System.Threading;

class MainClass
    {
        public static void Main()
        {
            string state = "Timer expired.";

            Console.WriteLine("{0} : Creating Timer.", DateTime.Now.ToString("HH:mm:ss.ffff"));

            using (Timer timer = new Timer(delegate(object s)
                            {Console.WriteLine("{0} : {1}",
                             DateTime.Now.ToString("HH:mm:ss.ffff"),s);
                            }
                , state, 2000, 1000))
            {
                int period;
                do
                {
                    try
                    {
                        period = Int32.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        period = 0;
                    }
                    if (period > 0) timer.Change(0, period);
                } while (period > 0);
            }
        }
    }

Result


Related Tutorials