VB.Net–Multiple Methods to Pause your Application

Posted by Blake on 2/10/2012
)

Here is a class with some static methods that will help you when you need to generate a pause in your code. Each is commented with what it does. Some block other threads and others are designed to allow them to continue processing (for a performance hit of course).

''' <summary>
''' Three subs to invoke different types of pausing techniques from API based calls that pause a 
''' whole process and all threads to programmatic async pauses in Windows and Console programs and
''' empty loop pauses that does not block other threads and allows them to continue processing.    
''' </summary>
Public Class Pause
    '*********************************************************************************************************************
    '
    '             Class:  Pause
    '      Initial Date:  09/16/2007
    '      Last Updated:  04/28/2009
    '     Programmer(s):  Blake Pell
    '
    '*********************************************************************************************************************

    ''' <summary>
    ''' Windows API call to kernel32.dll for the Sleep procedure.
    ''' </summary>
    ''' <param name="dwMilliseconds"></param>
    ''' <remarks></remarks>
    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Integer)

    ''' <summary>
    ''' Invokes the operating system API to pause the current process for the given amount of time.  All processing
    ''' ceases for this timeperiod.  
    ''' </summary>
    ''' <param name="milleseconds"></param>
    ''' <remarks></remarks>
    Public Shared Sub Pause(ByVal milleseconds As Integer)
        If milleseconds <= 0 Then Exit Sub
        Call Sleep(milleseconds)
    End Sub

    ''' <summary>
    ''' This is a programmatic pause meant only for Windows console or forms based applications.  This will allow other
    ''' threads to continue processing via Application.DoEvents().
    ''' </summary>
    ''' <param name="milleseconds"></param>
    ''' <remarks>Not suitable for ASP.NET.</remarks>
    Public Shared Sub AsyncPause(ByVal milleseconds As Integer)
        Dim sw As New Stopwatch
        sw.Start()
        While sw.ElapsedMilliseconds <= milleseconds
            System.Windows.Forms.Application.DoEvents()
        End While
        sw.Stop()
    End Sub

    ''' <summary>
    ''' Programmatic pause running an empty loop.
    ''' </summary>
    ''' <param name="milleseconds"></param>
    ''' <remarks></remarks>
    Public Shared Sub EmptyLoopPause(ByVal milleseconds As Integer)
        Dim sw As New Stopwatch
        sw.Start()
        While sw.ElapsedMilliseconds <= milleseconds
            ' Do nothing.
        End While
        sw.Stop()
    End Sub
End Class