blog vipa
mój dzień to 3 filiżanki kawy

blog vipa

.NET C# Timers

Marzec 18th, 2007 . by vip

The simplest method to add non-blocking ticker in C#:
[csharp]
using System.Threading;

public Clock()
{
System.Threading.Timer tmrThreadingTimer = new
System.Threading.Timer(new
TimerCallback(tmrThreadingTimer_TimerCallback),
null, System.Threading.Timeout.Infinite, 1000);
tmrThreadingTimer.Change(0, 1000);
}[/csharp]

And now, the ticking method:

[csharp]private void tmrThreadingTimer_TimerCallback(object state)
{
Console.WriteLine(„Now: {0}”, DateTime.Now.ToString(„T”));
}[/csharp]

The timer will start immediately after executing Change() method. You can also replace System.Threading.Timeout.Infinite (it causes timer do not start) with 0, and remove Change() method to do that same.
You can also create Your own object (which could store no of ticks, for example) and read/write to it in Callback method. The examples are on msdn and dotgnu.

That’s all, folks!

Leave a Reply