Link to home
Start Free TrialLog in
Avatar of XK8ER
XK8ERFlag for United States of America

asked on

1ms timer calling functions

Hi,
For testing purposes I have this timer that calls a function every 1ms and adds +1 to a counter. This code works perfectly fine as its calling windows native code but is there anything in the .NET framework even close to 1ms or shall I stick to using native calls?

Public Class Form1
    Dim mHandler As TimerEventHandler
    Dim iCount As Long = 0
    Dim mTimerId As Integer

    <DllImport("winmm.dll")>
    Private Shared Function timeSetEvent(delay As Integer, resolution As Integer, handler As TimerEventHandler, user As IntPtr, eventType As Integer) As Integer
    End Function

    <DllImport("winmm.dll")>
    Private Shared Function timeBeginPeriod(millisecond As Integer) As Integer
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        timeBeginPeriod(1)
        mHandler = New TimerEventHandler(AddressOf TimerCallback)
        mTimerId = timeSetEvent(1, 0, mHandler, IntPtr.Zero, 1)
    End Sub

    Private Delegate Sub TimerEventHandler(id As Integer, msg As Integer, user As IntPtr, dw1 As Integer, dw2 As Integer)
    Private Sub TimerCallback(id As Integer, msg As Integer, user As IntPtr, dw1 As Integer, dw2 As Integer)
        iCount += 1
    End Sub
End Class

Open in new window

Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

It's not quite clear what you want or what's required.

You may use stopwatch class to measure time elapsed: https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx
You may measure in milliseconds or in ticks. 1 tick - 100 ns.

Also you may use DateTime.Ticks property to measure times:
https://msdn.microsoft.com/en-us/library/system.datetime.ticks(v=vs.110).aspx
Avatar of XK8ER

ASKER

using DateTime is not a good suggestion as it has a resolution of about 15ms and also stopwatch is not good unless you use high resolution stopwatch.

the questions here is more of a concern than anything else, so i'm just worried if there are any casualties by using this code in a production environment or if it is a safe call.
ASKER CERTIFIED SOLUTION
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial