December 2017 : Online courses in ASP.NET MVC and Angular 4. Conducted by Bipin Joshi. Read more...
Registration for December 2017 batches of ASP.NET MVC / Core and Angular 4 online courses have already started. Conducted by Bipin Joshi. Book your seat today ! Click here for more details.

Using Timer Class

Introduction

If you have programmed in VB6 before then probably you are familiar with Timer control. The Timer control triggers a code after certain interval of time. This control is typically used on windows forms. Similar control does exists for Windows Forms as well. What if you need such timer functionality on a thread of your classes (not on forms)? The System.Threading.Timer class can be used in such cases. This class automatically uses Thread Pool for executing your code.

Namespaces Involved

Following namespaces are involved:
  • System
  • System.Threading

Using System.Threading.Timer Class

In order to use Timer class you need to create an instance of it as shown below:
Public Sub StartTimer()
  Dim tcb As New TimerCallback(AddressOf Me.TimerMethod)
  Dim objTimer As Timer
  objTimer = New Timer(tcb, Nothing, 
  TimeSpan.FromSeconds(5), 
  TimeSpan.FromSeconds(10))
End Sub

Public Sub TimerMethod(ByVal state As Object)
   MsgBox("The Timer invoked this method.")
End Sub
Here, we created an instance of Timer class and passed a TimerCallBack and interval details to it. The third parameter represents the delay in milliseconds after which the method will be called for the first time. The forth parameter represents the interval in milliseconds that will be elapsed between the consecutive method calls. In our example the timer will start 5 seconds after creation of the instance. Then after 10 seconds it will fire again and again.

Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 26 October 2002


Tags : .NET Framework VB.NET C# Components Multithreading