Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

There's no real limit on standard STA thread, but there is only one 'special' STA thread for the UI that has the message loop. This may be what you read elsewhere. While most COMs are fine with any STA thread, some COMs may require the message loop (such as for timer ticking) which will require pointing back to the UI thread or message pumping.

Is STA Message Loop Required in This Case?

http://blogs.msdn.com/b/cbrumme/archive/2004/02/02/66219.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top