views:

53

answers:

5

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.

A: 

don;t know vb, but all other languages i know have this operation for this kind of stuff: join().

int main(){
  threadA.start();
  threadA.join(); //here main() wait threadA end
  threadB.start(); //what you want
}

Sorry for not_vb.Wrote it cuz i expect the same function with the same name in VB.

foret
You'll have to do this in a third thread so you don't block the main one.
Jouke van der Maas
+4  A: 

Why not reuse the threads instead of spawning new ones? Other than that look at a pattern known as a producer/consumer queue. Your producer adds files (their path information), the consumers read that and take the appropriate action (perform the copy operation)

MaLio
Creating a thread does have a measurable overhead. Even using a ThreadPool, I found.
Kieren Johnstone
Even a tiny saving is a little saving, especially when you get it for free.I find reusing threads for the same (or repeated tasks) makes the app a little easier to debug. especially when you need to attach windbg.
MaLio
A: 

Create a task object, put tasks into a queue, then dequeue and process tasks in 3-4 different threads. Producer-consumer pattern.

Al Bundy
A: 

In .Net 4.0 this is very easy to do with tasks:

Dim a As new Task(AdressOf doWork).ContinueWith(AdressOf doOtherWork)

See here for more examples (in C#).

Jouke van der Maas
A: 

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
Brian Gideon