C#.net Timers
In this post, we will see how to use Timers in C#.net and VB.net. Example uses ElapsedEventHandler event handler. You can use timers to keep windows service running. Let's see both C#.net and VB.net examples of Timers in .net.
Timers in [C#] example
Timers in C#: we will use System.Timers namespace to create an instance of Timer.
using System;
using System.Timers;
namespace Csharp.TimerExample
{
class Program
{
static void Main(string[] args)
{
Timer t = new Timer(1000);
t.Elapsed += new ElapsedEventHandler(t_Elapsed);
t.Start();
Console.ReadLine();
}
static void t_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine(DateTime.Now.ToString());
}
}
}
Description
To the constructor of Timer, we have passed 1000 milliseconds. Every occurrence of elapsed time interval it calls a method t_Elapsed. Where we are printing current Datetime values
(Vb.net) Timers example
Imports System.Text
Imports System.Timers
Namespace Csharp.TimerExample
Class Program
Private Shared Sub Main(args As String())
Dim t As New Timer(1000)
AddHandler t.Elapsed, New ElapsedEventHandler(AddressOf t_Elapsed)
t.Start()
Console.ReadLine()
End Sub
Private Shared Sub t_Elapsed(sender As Object, e As ElapsedEventArgs)
Console.WriteLine(DateTime.Now.ToString())
End Sub
End Class
End Namespace
Output
1/3/2012 10:56:07 PM
1/3/2012 10:56:08 PM
1/3/2012 10:56:09 PM
1/3/2012 10:56:10 PM
1/3/2012 10:56:11 PM
1/3/2012 10:56:12 PM
1/3/2012 10:56:13 PM
1/3/2012 10:56:14 PM
1/3/2012 10:56:15 PM
1/3/2012 10:56:16 PM
1/3/2012 10:56:17 PM
1/3/2012 10:56:18 PM
1/3/2012 10:56:19 PM
1/3/2012 10:56:20 PM
1/3/2012 10:56:21 PM
1/3/2012 10:56:23 PM
1/3/2012 10:56:23 PM
1/3/2012 10:56:24 PM
1/3/2012 10:56:25 PM
1/3/2012 10:56:26 PM
1/3/2012 10:56:27 PM
1/3/2012 10:56:28 PM
It's very simple example of C# using Timers. Every tick of 1000 milliseconds, Attached event handler calls the given function. You can use Timers tick event to keep your windows service running.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5