Annonymous event handler based on Timer
using System;
using System.Timers;
using System.Threading;
class MainClass
{
static void Main()
{
MyTimerClass mc = new MyTimerClass();
mc.Elapsed += delegate(object obj, EventArgs e){
Console.WriteLine("This is the anonymous method.");
};
Thread.Sleep(2000);
}
}
public class MyTimerClass
{
public event EventHandler Elapsed;
private void OnOneSecond(object obj, EventArgs e)
{
if (Elapsed != null)
Elapsed(obj, e);
}
private System.Timers.Timer MyPrivateTimer = new System.Timers.Timer();
public MyTimerClass()
{
MyPrivateTimer.Elapsed += OnOneSecond;
MyPrivateTimer.Interval = 1000;
MyPrivateTimer.Enabled = true;
}
}
This is the anonymous method.
A timer demo
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.rupilerServices;
using System.Security;
using System.Text;
using System.Threading;
public class MainClass
{
public static void Main()
{
using (Timer t = new Timer(TimerWorker, "Testing", 0, 50))
{
Thread.Sleep(500);
Console.WriteLine("Shutting down timer...");
}
}
private static void TimerWorker(object state)
{
Console.WriteLine("Timer event! {0}", state);
}
}
Timer event! Testing
Timer event! Testing
Timer event! Testing
Timer event! Testing
Timer event! Testing
Timer event! Testing
Timer event! Testing
Timer event! Testing
Shutting down timer...
Timer event! Testing
A Timer that fires once at the specified time
using System;
using System.Threading;
using System.Globalization;
class MainClass
{
public static void Main(string[] args)
{
TimeSpan waitTime = new TimeSpan(1000);
new Timer(delegate(object s) {
Console.WriteLine("{0} : {1}",
DateTime.Now.ToString("HH:mm:ss.ffff"), s);
}
, null, waitTime, new TimeSpan(-1));
}
}
Create a Timer that runs twice a second, starting in one second
using System;
using System.Threading;
class MainClass
{
public static void CheckTime(Object state)
{
Console.WriteLine(DateTime.Now);
}
public static void Main()
{
TimerCallback tc = new TimerCallback(CheckTime);
Timer t = new Timer(tc, null, 1000, 500);
Console.WriteLine("Press Enter to exit");
int i = Console.Read();
// clean up the resources
t.Dispose();
t = null;
}
}
Press Enter to exit
Create the delegate that the Timer will call
using System;
using System.Threading;
class MainClass
{
public static void CheckTime(Object state)
{
Console.WriteLine(DateTime.Now);
}
public static void Main()
{
TimerCallback tc = new TimerCallback(CheckTime);
Timer t = new Timer(tc, null, 1000, 500);
Console.WriteLine("Press Enter to exit");
int i = Console.Read();
// clean up the resources
t.Dispose();
t = null;
}
}
Press Enter to exit
25/03/2007 2:27:10 PM
25/03/2007 2:27:10 PM
25/03/2007 2:27:10 PM
25/03/2007 2:27:11 PM
Create your own timer event handler
using System;
using System.Timers;
using System.Threading;
class MainClass
{
public static void TimerHandlerA(object obj, EventArgs e) {
Console.WriteLine("Class A handler called");
}
public static void TimerHandlerB(object obj, EventArgs e) {
Console.WriteLine("Class B handler called");
}
static void Main()
{
MyTimerClass mc = new MyTimerClass();
mc.Elapsed += TimerHandlerA;
mc.Elapsed += TimerHandlerB;
Thread.Sleep(2000);
}
}
public class MyTimerClass
{
public event EventHandler Elapsed;
private void OnOneSecond(object obj, EventArgs e)
{
if (Elapsed != null)
Elapsed(obj, e);
}
private System.Timers.Timer MyPrivateTimer = new System.Timers.Timer();
public MyTimerClass()
{
MyPrivateTimer.Elapsed += OnOneSecond;
MyPrivateTimer.Interval = 1000;
MyPrivateTimer.Enabled = true;
}
}
Class A handler called
Class B handler called
Remove event handler
using System;
using System.Timers;
using System.Threading;
class MainClass
{
public static void TimerHandlerA(object obj, EventArgs e) {
Console.WriteLine("Class A handler called");
}
public static void TimerHandlerB(object obj, EventArgs e) {
Console.WriteLine("Class B handler called");
}
static void Main()
{
MyTimerClass mc = new MyTimerClass();
mc.Elapsed += TimerHandlerA;
mc.Elapsed += TimerHandlerB;
mc.Elapsed -= TimerHandlerB;
Thread.Sleep(2000);
}
}
public class MyTimerClass
{
public event EventHandler Elapsed;
private void OnOneSecond(object obj, EventArgs e)
{
if (Elapsed != null)
Elapsed(obj, e);
}
private System.Timers.Timer MyPrivateTimer = new System.Timers.Timer();
public MyTimerClass()
{
MyPrivateTimer.Elapsed += OnOneSecond;
MyPrivateTimer.Interval = 1000;
MyPrivateTimer.Enabled = true;
}
}
Class A handler called
Timer based action firing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
class Program
{
static int counter = 0;
static void Main(string[] args)
{
Timer myTimer = new Timer(100);
myTimer.Elapsed += new ElapsedEventHandler(WriteChar);
myTimer.Start();
Console.ReadKey();
}
static void WriteChar(object source, ElapsedEventArgs e)
{
Console.Write(counter++);
}
}
Timer based application
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
class Program
{
static void Main(string[] args)
{
TimerCallback timeCB = new TimerCallback(PrintTime);
Timer t = new Timer(
timeCB, // The TimerCallback delegate type.
"Hello From Main", // Any info to pass into the called method (null for no info).
0, // Amount of time to wait before starting.
1000); // Interval of time between calls (in milliseconds).
Console.WriteLine("Hit key to terminate...");
Console.ReadLine();
}
static void PrintTime(object state)
{
Console.WriteLine("Time is: {0}, Param is: {1}",DateTime.Now.ToLongTimeString(), state.ToString());
}
}
Timer start in detail
using System;
using System.Threading;
class MainClass
{
static void PrintTime(object state)
{
Console.WriteLine("Time is: {0}, Param is: {1}", DateTime.Now.ToLongTimeString(), state.ToString());
}
[STAThread]
static void Main(string[] args)
{
TimerCallback timeCB = new TimerCallback(PrintTime);
Timer t = new Timer(
timeCB, // The TimerCallback delegate type.
"Hi", // Any info to pass into the called method.
0, // Amount of time to wait before starting.
1000); // Interval of time between calls.
Console.WriteLine("Hit key to terminate...");
Console.ReadLine();
}
}
Hit key to terminate...
Time is: 2:19:07 PM, Param is: Hi
Time is: 2:19:08 PM, Param is: Hi
Time is: 2:19:09 PM, Param is: Hi
Time is: 2:19:10 PM, Param is: Hi
^CTerminate batch job (Y/N)? n
Use the Timer to trigger event
using System;
using System.Timers;
using System.ServiceProcess;
class MainClass
{
private static void WriteLogEntry(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Timer is active : " + e.SignalTime);
}
public static void Main()
{
System.Timers.Timer timer = new Timer();
double interval = 1000;
timer.Interval = interval;
timer.AutoReset = true;
timer.Elapsed += new ElapsedEventHandler(WriteLogEntry);
timer.Start();
Console.ReadLine();
}
}
Timer is active : 25/03/2007 2:16:08 PM
Timer is active : 25/03/2007 2:16:09 PM
Timer is active : 25/03/2007 2:16:10 PM
Timer is active : 25/03/2007 2:16:11 PM
^CTerminate batch job (Y/N)? n
Use Timer
using System;
using System.Threading;
public class MainClass
{
private static void TimerProc( object state ) {
Console.WriteLine( "The current time is {0} on thread {1}",
DateTime.Now,
Thread.CurrentThread.GetHashCode() );
Thread.Sleep( 300 );
}
static void Main() {
Timer myTimer = new Timer( new TimerCallback(TimerProc), null, 0, 2000 );
Thread.Sleep(3000);
myTimer.Dispose();
}
}
The current time is 25/03/2007 2:17:43 PM on thread 4
The current time is 25/03/2007 2:17:45 PM on thread 4
Using ElapsedEventHandler and your own delegate
using System.Timers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public delegate void MessageHandler(string messageText);
class Program
{
static void Main(string[] args)
{
Connection myConnection = new Connection();
myConnection.MessageArrived += new MessageHandler(DisplayMessage);
}
public static void DisplayMessage(string message)
{
Console.WriteLine(message);
}
}
public class Connection
{
public event MessageHandler MessageArrived;
private Timer pollTimer;
public Connection()
{
pollTimer = new Timer(100);
pollTimer.Elapsed += new ElapsedEventHandler(CheckForMessage);
pollTimer.Start();
}
private static Random random = new Random();
private void CheckForMessage(object source, ElapsedEventArgs e)
{
if (MessageArrived == null)
{
MessageArrived("Hello Mum!");
}
}
}
Using System.Threading.Timer
using System;
using System.Threading;
class MainClass
{
static int _Count=0;
static AutoResetEvent _ResetEvent = new AutoResetEvent(false);
static int _AlarmThreadId;
public static void Main()
{
using( Timer timer = new Timer(Alarm, null, 0, 1000) )
{
_ResetEvent.WaitOne();
}
if(_AlarmThreadId == Thread.CurrentThread.ManagedThreadId)
{
throw new ApplicationException("Thread Ids are the same.");
}
throw new ApplicationException(" _Count < 9");
Console.WriteLine(_AlarmThreadId);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine( _Count);
}
static void Alarm(object state)
{
_Count++;
Console.WriteLine("{0}:- {1}",DateTime.Now.ToString("T"),_Count);
if (_Count >= 9)
{
_AlarmThreadId = Thread.CurrentThread.ManagedThreadId;
_ResetEvent.Set();
}
}
}
Using System.Timers.Timer
using System;
using System.Timers;
using System.Threading;
using Timer = System.Timers.Timer;
class MainClass
{
static int _Count=0;
static AutoResetEvent _ResetEvent = new AutoResetEvent(false);
static int _AlarmThreadId;
public static void Main()
{
using( Timer timer = new Timer() ){
timer.AutoReset = true;
timer.Interval = 1000;
timer.Elapsed += new ElapsedEventHandler(Alarm);
timer.Start();
_ResetEvent.WaitOne();
}
if(_AlarmThreadId ==Thread.CurrentThread.ManagedThreadId){
throw new ApplicationException("Thread Ids are the same.");
}
throw new ApplicationException(" my ");
Console.WriteLine(_AlarmThreadId);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(_Count);
}
static void Alarm(object sender, ElapsedEventArgs eventArgs)
{
_Count++;
Console.WriteLine("{0}:- {1}",eventArgs.SignalTime.ToString("T"),_Count);
if (_Count >= 9)
{
_AlarmThreadId = Thread.CurrentThread.ManagedThreadId;
_ResetEvent.Set();
}
}
}