public class ManageThreads
{
private Thread doStuffThread = null;
//Inside the constructor EVERY thread is instantiated and run.
//(I am aware that this example only shows the use of 1 thread).
public ManageThreads()
{
doStuffThread = new Thread(new ThreadStart(DoSomeStuff.Instance.Start));
doStuffThread.Start();
//Instantiate and run another thread.....
//Instantiate and run another thread.....
//Instantiate and run another thread.....etc.
}
}
public class DoSomeStuff
{
void Start()
{
while(true)
{
//Repeatedly do some tasks.....
Thread.Sleep(5000);
}
}
}
Help greatly appreciated.
"I get the feeling this design element has an impact on performance."
Don't guess, get a profiler out and measure what's going on. Gather some empirical stats about where time is spent in the application and then you can take a view on where the pinch points are.
If the time spent creating threads is your biggest headache then moving to a threadpool may be the right answer, but you won't know without some forensic analysis.
From the small snippet you've posted it looks like the 14 threads are reasonably long-lived, doing multiple things over their lifetime so I suspect that this is not the problem actually, but there isn't enough info in your post to make a definitive call on this.
if your threads are all doing work and you have more threads active than processors then you are going to be spending time context switching.
If you have a dual core processor dont expect to get great performance with more than 4 active working threads.
So starting off 14 threads that are all doing work is a bad idea unless you have a processor that can manage this. Physical processor architecture and feature set has a big impacrt on this. My point is that a threadpool will help manage the context switching but starting 14 busy threads at once is always gonna kill performance ... you will probably get faster performance from simply excuting the threads sequentially. Obviously that is a big statement and so is probably not trus, but you get the gist.
Hence the use of a thread pool along with a profiler to figure out the optimum number of threads to make available to the thread pool.
In most situations when people are usign a thread pool a lot of the threads are doing nothing most of the time, or a thread is sleeping/blocking whilst some slow operation or external dependancy awaits a response.
consider using an asynch pattern so that you can get info about progress out of your threads.
On a dual core processor i would be hesitant abou tusing more than 3 threads if they are all working 100% of the time
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.