开发者

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 th开发者_StackOverflow中文版at count of thread should remain 3 or 4. So how could i apply check on that ? please provide some information on it.


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)


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


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#).


I 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. I wrote it because I expect the same function with the same name in VB.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜