I’m reading C# in a nutshell 4.0 – great reading! The best I ever had on .NET framework.
I’ve just finished Chapters 21/22/23, I thought I knew something about threading, but I seems I don’t 🙂 I was suprissed when reading about AMP (Asynchronous Method Pattern) and how it enables thread economy, and its comparsion to ordinary thread usage.
Bottom line:
I always thought that if I had a thread, and when that thread is doing something and then is waiting for condition (like Monitor.Pulse), all the stack information used by that thread is freezed. While waiting for that particular condition, thread can be reused to serve another task. So basically: 1 thread can execute multiple code paths at the same time. But obviously I was wrong. So my question is:
- when tread starts, code it is executing is always the same (until code finishes and thread can be reused when talking about ThreadPool) ?
- if so, when executing a long-running task, if I access ManagedThreadId property I will always get the same id?
For both question: YES.
ThreadPoolreuses threads that are not doing work, basically there is a daemon that cares about all the pool threads: if they are more than ThreadPool.MinThreads they will be deleted, otherwise they will be reused to do new work whenThreadPool.QueueWorkUserItemwill be called.So: until your work inside a thread hasn’t finished it will not be deleted/reused also if you are using waiting mechanisms like Monitor.Wait / Monitor.Pulse 🙂