Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Delay without thread.sleep()

Posted on 2007-04-04
Medium Priority
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 500 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


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
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, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA:…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

721 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