I need multiple STA
threads inside my ASP.NET application to use some COM
components.
I read somewhere inside each process, only one STA
thread can exist. I coded a sample project and made many threads and set their apartment state to STA
and they work with COM
objects without any exception.
Is it possible to have many STA
threads inside a process ?
There is no inherent limit to the number of STA threads you can have, however you will probably want to impose such a limit on your own.
If you allow your ASP.NET application to create additional STA threads as new user requests arrive, without limiting it, eventually the number of threads will cause your application's performance to deteriorate as the amount of time spent by the CPU on context switching becomes too high. This also makes your application much more vulnerable to denial of service attacks.
You can consider a design were you set a limit for the number of STA threads based on your hardware or users profile, and once the limit is reached, implement some pooling to re-use existing STA threads to service new requests.
If your program works with many STA threads, then why do you ask if it works? :) .NET allows you to have any number of STA threads, so it must work. What you read might be true for typical native applications with only one main thread and a message loop, though.
There is no upper limit, other than memory. A 32-bit process normally peters somewhat shy of 2000 threads when the stacks of the threads have consumed all available address space.
Keep the rules in mind, you cannot call an object that was created in one STA from another STA without marshaling. And don't forget the required message loop, an STA thread must pump to keep the marshaling alive and prevent deadlock. Obviously getting anywhere close to the memory limit should be strongly avoided.
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