Search code examples
vb.netmultithreadingwindows-services

how to start new thread as soon as previously thread gets finished?


i have to develop windows service which will copy files to different servers. So i have to do this task using multi-theading. But i have to start only 3-4 threads. So whenever one threads get finished then i have to start new thread so that count of thread should remain 3 or 4. So how could i apply check on that ? please provide some information on it.


Solution

  • This might give you a starting point. The idea is to use a blocking queue which will block on the dequeue operation until an item is available. So your worker threads will spin around an infinite loop waiting for items to appear in the queue. Your main thread will enqueue the items into the queue. The following example uses the BlockingCollection class from the .NET 4.0 BCL. If that is not available to you then you can get an implementation of a blocking queue from Stephen Toub's blog.

    Module Example
    
        Private m_Queue As BlockingCollection(Of String) = New BlockingCollection(Of String)
    
        Sub Main()
    
            Dim threads(4) As Thread
            For i As Integer = 0 To threads.Length - 1
                threads(i) = New Thread(AddressOf Consumer)
                threads(i).IsBackground = True
                threads(i).Start()
            Next
    
            Dim files As IEnumerable(Of String) = GetFilesToCopy()
    
            For Each filePath As String In files
                m_Queue.Add(filePath)
            Next
        
        End Sub
    
        Sub Consumer()
            Do While True
                Dim filePath As String = m_Queue.Take()
                ' Process the file here.
            Loop
        End Sub
    
    End Module