Interested on Microsoft technologies? Read Visual Studio Dot Net

Tutorial 4: Avoiding the Timer Control

Reason of this project:
I have done a long search on this theme. I have already published 2 tutorials on how to use timer.
Now I found a method with vb.net on how to count without using the timer control.
This can be helpful if you are using a Command Line Application

Project details:
1- How this work?
2- A small sample
3- The stopwatch class

1- How this work?

It works exactly like the timer work! The stopwatch is a class that can help you count.
To declare this class use this line of code:
Imports System.Diagnostics.Stopwatch
This line must be left in the top of the code before anything.
I'll introduce in the 2d sample how to use the stop watch class.
However in the next sample, I'll show a simple method to avoid using the timer control and the Stopwatch also.


2- A small sample

Our aim here is to calculate the time elapsed between 2 different steps in the program.
This task seems to be complex and need a timer. But we'll do it without a timer in a very simple method.
How this is done?
The Now.tick return a time (don't matter what it return), however this time change regularly. (It's a real counter).
Between the two steps we'll calculate the difference and divide it by 10,000,000. (Because Tick precision is Nano-second!!).
This is the code so far:
Dim First As Long
Dim second As Long
Dim time As Double
First = Now.Ticks
MsgBox("OK to see counted time")
second = Now.Ticks
time = (second - First) / 10000000
MsgBox("Time in seconds: " & time.ToString())

See the sample for more information (Commented)


3- The stop watch

The previous method is helpful but can be limited to work with.
The stop watch will solve the problem. It's a class that exist in the .net Frame Work.
To declare this class use this line of code:
Imports System.Diagnostics.Stopwatch
This line must be left in the top of the code before anything.
I have already mentioned this, but although people don't see it and then have a problem when trying to run their application.
If you don't import the class you can't work with it!
What's the stopwatch class? It's a stopwatch!
How it works? exactly like the timer control, we can say that it's a timer control.
This is the line that will create a new stopwatch
Dim mystopwatch As New System.Diagnostics.Stopwatch

We'll start counting with the following line.
mystopwatch.Start()

And we'll get the elapsed time with
mystopwatch.Elapsed.Totalseconds

You can see the source code in the 2nd sample for more details.


Download Source Code

The Zip file contains:
-The two example source code
-The readme.txt file
-The tutorial.txt file

Still have question:
If you have any problem or you found a bug, post a comment describing your problem.
If you have a general question, we highly recommend the MSDN Forums as the best Dot Net forums in the net.

Bookmark and share this tutorial
Related Ads

0 comments:

Related articles