randy1200 said:
Say you've got a bunch of different panels, and each panel has it's own
background worker that you've dragged out of the toolbox. This all works
great, but it takes some effort to figure out which thread goes with which
panel. It would be nice to look at the Name property in the thread window
of
the debugger.
Don't tell me you burn a thread for each panel on your UI, this is a sign
for a bad design, really. Some reasons not to use worker threads from the
pool:
1. Worker threads are by design initialized to enter the MTA, UI threads
NEED to run in an STA thread that pumps the windows message queue, MTA
threads don't pump the queue, not respecting this simple rule will lead to
deadlocking.
2. Each thread consumes 1MB of comitted stack space, this means that if you
have 20 panels, you are wasting 20MB of private memory. No big deal you say,
wel assume your applicaton is run on Terminal Server, by say 100 users. Here
you waste 100 X 20MB = 2GB of memory (private remember!) as stack space, bed
this customer will not be happy at all :-((
3. The number of threads in the pool are restricted (25 per process per
processor), using too many of them can easely lead to deadlocks, especially
when using them for UI related code.
4. The underlying GDI (and GDI+) code is single threaded by design, so you
won't take any performance advantage when running UI code in different
threads, to the contrary, you will incur a (small) performance hit when
doing so.
Therefore I would suggest you to use them only for short running tasks (say
a couple of seconds at most).
You rarely need to handle UI stuff in different threads, and if you really
think you need to, just use regular threads, which you can control yourself,
you can name the threads, and you can initialize them to enter a STA.
Currently, assigning a Name to a thread more than once will throw an
exception. My thought is that if Microsoft could add a mechanism to allow
name assignment when background worker grabs a thread out of the thread
pool,
then remove any assigned name when the thread is returned to the pool.
But that's exactly the point , a thread in the pool (really an OS thread)
is created once, it stays in the pool once created, you can't change the
name of a thread you can only name a thread when he gets created. You
don't want the thread to return to the OS and make the CLR to recreate the
thread just because you want it to give a name do you? this would completely
defeat the purpose of the pool.
During debugging, using the Debug->Windows->Threads window can be a
life-saver, and of course, this is where the names show up.
No, what they should do is display the managed thread ID next to the (OS)
thread ID, note that this is something you can do yourself in the Immediate
window , just type:
? Thread.CurrentThread.ManagedThreadId
and you'll get the managed thread Id back, just write it down .
Willy.
Willy.