Delay without thread.sleep()

Posted on 2007-04-04
Last Modified: 2012-06-22
Hi All,

Is there a way to delay stuff in without using thread.sleep().  I would explain, but it's a long story.

Thank you!
Question by:schnibitz
  • 2
  • 2
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 18854482
Use one of the Timer controls and set the Interval accordingly.

Otherwise create a new Thread and put THAT to sleep for the required time (or poll on the new thread).

If that doesn't help you then please explain the "long story"...


Author Comment

ID: 18854537
Hi There,
The critical part of this code is the copyfile() sub, which is actually the last one.  Silly me, I thought that the thread.sleep() method would do the trick, but it literally shuts down everything for some reason, making it so that it won't detect any new file creation events at all.

Obviously I wouldn't want that.  I checked out the timer thing you suggested and it looks interesting, but it would require rearranging some of my code (I think) and I'd rather not do that being the skittish n00b that I am.

I was wondering if a do until loop that gets the time now, and adds 1 minute it then keeps running until now + 1 minute would work?  I just need something quick and dirty, but something that won't shut down my thread.

Imports System.ServiceProcess
Imports System.Threading

Public Class Service1
    Inherits System.ServiceProcess.ServiceBase
    Dim DestDirectory As String
    Dim WatchDirectory As String
    Dim SourceFilePath As String
    Dim SourceFileName As String
    Dim MyQueue As New Queue
    Dim MyRetValue As New Queue
    Dim DQedSrceFilePath As String
    Dim DestPath As String
    'Private CopyF As New Thread(New System.Threading.ThreadStart(AddressOf CopyFile))
    Private Watchservice As New Thread(New System.Threading.ThreadStart(AddressOf StartMonitor))

#Region " Component Designer generated code "

    Public Sub New()

        ' This call is required by the Component Designer.

        ' Add any initialization after the InitializeComponent() call

    End Sub

    'UserService overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
            End If
        End If
    End Sub

    ' The main entry point for the process
    <MTAThread()> _
    Shared Sub Main()
        Dim ServicesToRun() As System.ServiceProcess.ServiceBase

        ' More than one NT Service may run within the same process. To add
        ' another service to this process, change the following line to
        ' create a second service object. For example,
        '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
        ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}

    End Sub

    'Required by the Component Designer
    Private components As System.ComponentModel.IContainer

    ' NOTE: The following procedure is required by the Component Designer
    ' It can be modified using the Component Designer.  
    ' Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.ServiceName = "Service1"

    End Sub

#End Region

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Start the thread.
    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
    End Sub
    Private Sub StartMonitor()
        'This code is obviously a service that will listen for created files in a directory,
        'definied as watchdirectory below, and copy them to the DestDirectory defined below.

        WatchDirectory = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\CopyMon", "Source", Nothing)
        DestDirectory = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\CopyMon", "Destination", Nothing)

        Dim watcher As New System.IO.FileSystemWatcher(WatchDirectory)
            'If a create event is detected, kick off the logchange sub which
            'will add the pathing info to a queue
            AddHandler watcher.Created, AddressOf logchange
            'If a create even is detected, kick off the CopyFile sub
            'which will pull paths of created files from the queue
            'and copy them to the DestDirectory defined above
            AddHandler watcher.Created, AddressOf CopyFile
            'Initialize the watchers.
            watcher.EnableRaisingEvents = True
        Catch ex As Exception
            My.Application.Log.WriteException(ex, _
                TraceEventType.Error, _
                "Exception in ExceptionLogTest " & _
                "with argument " & ".")
        End Try
    End Sub
    Private Sub logchange(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)

        SourceFilePath = e.FullPath
        SourceFileName = e.Name
        'Try to add the sourcefile path to the queue
            MyRetValue = queue.Synchronized(MyQueue)
        Catch ex As Exception
            My.Application.Log.WriteException(ex, _
                TraceEventType.Error, _
                "Exception in ExceptionLogTest " & _
                "with argument " & ".")
        End Try
    End Sub
    Private Sub CopyFile(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)

        'Sleep for a minute in case something needs to make changes to the file.
        'Loop through the queue until there is nothing left.  Copy any files that are there.
        Do Until MyQueue.Count = 0
                DQedSrceFilePath = MyQueue.Dequeue()
                MyRetValue = queue.Synchronized(MyQueue)
                DestPath = DestDirectory & "\" & SourceFileName
            Catch ex As Exception
                My.Application.Log.WriteException(ex, _
                    TraceEventType.Error, _
                    "Exception in ExceptionLogTest " & _
                    "with argument " & ".")
            End Try

                My.Computer.FileSystem.CopyFile(DQedSrceFilePath, DestPath)
            Catch ex As Exception
                My.Application.Log.WriteException(ex, _
                    TraceEventType.Error, _
                    "Exception in ExceptionLogTest " & _
                    "with argument " & ".")
            End Try
    End Sub

End Class
LVL 85

Accepted Solution

Mike Tomlinson earned 125 total points
ID: 18854570
Here is what you could do in a traditional WinForm app:

    Private Sub Delay(ByVal DelayInSeconds As Integer)
        Dim ts As TimeSpan
        Dim targetTime As DateTime = DateTime.Now.AddSeconds(DelayInSeconds)
            ts = targetTime.Subtract(DateTime.Now)
            Application.DoEvents() ' keep app responsive
            System.Threading.Thread.Sleep(50) ' reduce CPU usage
        Loop While ts.TotalSeconds > 0
    End Sub

But I see you have a SERVICE and I don't know what caveats there are to calling Application.DoEvents() from a service.  =(

Author Comment

ID: 18855457
Believe it or not that suggestion worked great.  Thank you!

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now