I am trying to load a queue of interval processes. In other words, I have a queue, and I want each element in the queue to run on a separate interval.
My problem is that I cannot start more than 25 threads to start at one time. I use .Net 4.5 on a 64-bit machine, which has a maximum number of threads by default of 32768.
How to make my application run as many simultaneous threads as my machine can handle?
Here is an example application that replicates the actual problem in my production code:
class Program { static void Main(string[] args) { System.Threading.ThreadPool.SetMaxThreads(200, 200); test t = new test(); t.LoadUrls("http://www.google.com"); while (1 == 1) { System.Threading.Thread.Sleep(1000);
This code should theoretically start 198 threads in 2 seconds or so.
By the way, this worked great in my application prototype; it was written in node. But now I can not get it to work correctly in C # ...
ANSWER: The problem was actually garbage collection and was not a thread problem at all; the pool is more than capable of winding all the threads that I throw at it. The trick is to use the single parameter constructor System.Threading.Timer; this will force the timer to use itself as a semaphore, while avoiding gc.
class Program { static void Main(string[] args) { for (int i = 0; i < 100; i++) { test t = new test(); t.url = "http://www.google.com?" + i; System.Threading.Timer ti = new System.Threading.Timer(new System.Threading.TimerCallback(t.RunInterval)); ti.Change(0, 1000); } while (1 == 1) System.Threading.Thread.Sleep(int.MaxValue); } public class test { public string url { get; set; } public void RunInterval(object state) { Console.WriteLine("getting data for " + this.url); string data = ""; using (System.Net.WebClient cl = new System.Net.WebClient()) { data = cl.DownloadString(this.url); } } } }
I'm not sure why you ever want a timer built by gc, but hey, what I know.
Eulalie367
source share