On Jun 12, 9:20*am, Curious <fir5tsi...@yahoo.comwrote:
Are you saying that if a task is complicated, use Thread instead of
thread pool? What are the differences between thread and thread pool
exactly?
Thread represents a single logical thread of execution. ThreadPool is
a manager for a pool of threads that are always available to execute
work items. The advantage of the ThreadPool is that it keeps its
constituent threads initialized and running so that they can begin
executing work items immediately as they arrive. There would be no
overhead for creating a new thread and getting it running. The caveat
is that it works better if the work items can be completed quickly so
that the threads executing them can return to the pool in a timely
manner.
Think about it this way. Assume that it takes 100 CPU cycles to
initialize a new thread. Now assume that your work item takes 100 CPU
cycles to complete. The ratio of overhead to actual work is a
whopping (and unappealing) 0.5. Now assume your work item takes
10,000 cycles to complete. The ratio is now only 0.005. So in the
first example you could cut the execution time in half by using the
ThreadPool instead of spinning up a new Thread. But, in the second
example the benefit is negligible. In other words, spinning up a new
Thread in the second example doesn't effect performance all that much.
>
What if I need to show a message box periodically, shall I use thread
or thread pool? If the user is in a long meeting and doesn't click
"OK" button to dismiss the message box, potentially there may be whole
bunch of message boxes clustered on the screen.
ThreadPool versus Thread is irrelevant in this case. The execution of
your work item is a non-UI thread period. Special care needs to be
taken when attempting to interact with the UI from a non-UI thread.
In fact, you can't technically do anything to the UI (show a message
box or even read a Form variable) from a thread other than the UI
thread. If you want the work item to signal or communicate to the UI
thread then you need to marshal the execution of a method onto the UI
thread. This can be done via the Control.Invoke or
Control.BeginInvoke methods.
Thanks! I'll use Thread then.