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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
LVL 86

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 86

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

630 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