• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1053
  • Last Modified:

Delay without thread.sleep()

Hi All,

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

Thank you!
0
schnibitz
Asked:
schnibitz
  • 2
  • 2
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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"...

0
 
schnibitzAuthor Commented:
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()
        MyBase.New()

        ' This call is required by the Component Designer.
        InitializeComponent()

        ' 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
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    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}

        System.ServiceProcess.ServiceBase.Run(ServicesToRun)
    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()
        '
        'Service1
        '
        Me.ServiceName = "Service1"

    End Sub

#End Region

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

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
        Watchservice.Abort()
    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)
        Try
            '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.InternalBufferSize.Equals(4000960)
            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
        Try
            MyQueue.Enqueue(SourceFilePath)
            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.
        'Thread.Sleep(60000)
        'Loop through the queue until there is nothing left.  Copy any files that are there.
        Do Until MyQueue.Count = 0
            Try
                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

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

End Class
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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)
        Do
            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.  =(
0
 
schnibitzAuthor Commented:
Believe it or not that suggestion worked great.  Thank you!
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now