c# new thread from timer handle issue
Im experimenting with the following code
private void timer1_Tick(object sender, EventArgs e)
{
Thread nT = new Thread(new ThreadStart (checkThread));
nT.Start();
}
The cheackThread() function carries out a web-request and the timer's开发者_开发百科 tick property is 2000ms. All objects in the checkThread() are disposed of after use. When the program is run for long periods e.g 3 hours the OS complains about low resources. I notices that in ctrl-alt-delete the handle count is increasing when the app runs. Does the thread not release its memory automatically once it has executed all its code or is this one of those times gc.collect is permitted?
the timer's tick property is 2ms
First, your timer will not honor this. The resolution is ~20 ms.
But even 20 ms is not very long for a Webrequest. If your checkThread exceeds 20ms (every now and then) then you would be starting Threads quicker than they can finish. And so they pile up. The fact that it takes a few hours makes me think this is the most likely cause.
You could use a debugger, or a simple counter activeThreads
(use Interlocked) to diagnose this.
Using the ThreadPool or the TPL (Fx4) would solve some of your issues but you would still need to check and limit the number of simultaneous requests.
You should let the Framework handle the threads, instead of using Thread
go for ThreadPool.QueueUserWorkItem
精彩评论