I have a question about threads, the thread pool for ASP.net and Unity's Thread Scope object scope. From what I understand, each request for an ASP.net site gets its own thread & when the request is finished the thread goes back to the thread pool. Is that correct?
If that is true then how does that affect the use of Thread Scope in Unity? If we use that and the thread ends up back in the thread pool, does the Unity object just stick around? Does the thread do any garbage collection on it's variables when its sent to the pool? It must do something like since it handles different requests.
I guess my question is, when exactly are threads garbage collected?
Unity Object Scope Definitions
Note that a .NET Thread object is not the same as the thread that it represents. The latter is an operating system concept and even though .NET threads have been abstracted away from Windows threads you can assume that a .NET thread gets its ability to execute code from a Windows thread unless you are in an exotic environment.
I guess my question is, when exactly are threads garbage collected?
Thread objects can only be garbage collected when the associated thread has terminated and the Thread is no longer reachable from any GC roots. Thread objects in the .NET thread pool does not get garbage collected as long as they are in the thread pool.
If you use PerThreadLifetimeManager in Unity then there will be a separate instance for each thread. Each call to Resolve from the same thread will return the same instance but calls to Resolve from different threads will return different instances.
Note that PerThreadLifetimeManager will not dispose any instances when the associated thread terminates.
If you use async and await in your ASP.NET code a single request may be processed by multiple threads.
PerThreadLifetimeManager is built on top of thread local storage and can be used to improve performance in multithreaded code. However, thread local storage is often confusing and in my opinion should not be used unless it is really necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With