Hi Everyone,
I have a multithreading application, a typical Main thread that uses
the ThreadPool.QueueUserWorkItem method to add new threads to the
Thread POOL.
I need a way to control the threads created by the thread pool because
some created threads go indefinilty for a long period of time and I
would like to terminate these threads.
I know that I can set a timeout for a thread but that's only when I use
the Thread class shared methods like Thread.Start, but with threadpool
I don't really know how to do that.
I also use AutoResetEvent object to wait for unfinished threads. does
this sound like a way to suspend threads started by the threadpool
class?
here is a snippet of the code: notice at the bottom of the code, I save
crete AutoResetEvent objects in arraylist, so that I can iterate
through it and wait for unfinished threads.
While True
If rowCounter > sitesDataTable.Rows.Count - 1 Then 'we
have reached the end of the datatable
Exit While
End If
'make sure you don't exceed the maximum of the pool
(default is always 25 thread per pool)
WaitForThreads()
'get the current row from the datarow
dtrow = sitesDataTable.Rows(rowCounter)
'prepare for the new thread
Dim MyThreadNotify As AutoResetEvent = New
AutoResetEvent(False)
m_newThreadsPoolArr.Add(MyThreadNotify)
'create a new instance of the processfeed class
Dim ProcessSingleFeedInstance As ProcessSingleFeed =
New ProcessSingleFeed
'set the input parameters
ProcessSingleFeedInstance.ConnectionString =
_connectionString
ProcessSingleFeedInstance.siteid = dtrow("id")
ProcessSingleFeedInstance.feedUrl =
IIf(IsDBNull(dtrow("feedurl")), "", dtrow("feedurl"))
ProcessSingleFeedInstance.feedType =
IIf(IsDBNull(dtrow("feedtype")), "1", dtrow("feedtype"))
'add the thread to the pool
Dim queueStatus As Boolean
queueStatus = ThreadPool.QueueUserWorkItem(New
WaitCallback(AddressOf ProcessSingleFeedInstance.parsefeed),
MyThreadNotify)
'give it enough time to start
Thread.Sleep(500)
printAvailThreads()
constructLog("thread added to the pool")
'advance to the next row for the next while loop
rowCounter = rowCounter + 1
If rowCounter Mod 25 = 0 Then 'every 25 loops, write
the string builder to the log file.
FlushToLog()
End If
End While
constructLog("while loop is done!")
printAvailThreads()
'make sure that all threads are done before quiting
constructLog("waiting for unfinished threads.")
FlushToLog()
Dim o As AutoResetEvent
For Each o In m_newThreadsPoolArr
Dim myt As AutoResetEvent
myt = o
'myt.WaitOne(15 * 1000, False)
myt.WaitOne()
Next