Sathishkumar Sathishkumar - 1 year ago 127 Question

.NET Thread Finalizer thread issue

I have below piece of code in my application. The applicaiton is an WindowsService and DoSomethingInTheading method is fired once the service is started.

Public Sub DoSomethingInThreading()
While True
Dim completeEvent As New ManualResetEvent(False)
Dim thread as Thread = New Thread(AddressOf DoSomeThingElse)
If Not completeEvent.WaitOne(120000) Then
Throw New SystemException("Issue in terminating")
End If
End While
End Sub

Public Sub DoSomeThingElse(Dim state as Object)
Dim finishEvent as ManualResetEvent = DirectCast(state, ManualResetEvent)
'Do I/O operation, this doesnt take more time (hardly in seconds)
End Sub

Now everything is seems to be fine when I have around 2500~3000 threads. Once it starts to build up after this limit I get application running out of memory or sometimes the application stops to respond. My assumption was that after the task is finished thread will be cleared up by GC (meaning in Finalizer thread).

My questions are:

  1. Are threads collected by Finalizer thread as it do for other objects?

  2. Do I need to manually implement any cleaning up threads? Won't it taken care by CLR?

  3. I application is .NET 3.5. I know that I can go ahead with ThreadPool and TPL but due to various reasons I need to stick to .NET 3.5

Any suggestions/helps - much appreciated.

Answer Source

.Net 3.5 still allows ThreadPool (it just doesn't allow TPL). To launch a thread simply do:

System.Threading.ThreadPool.QueueUserWorkItem(AddressOf DoSomethingElse)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download