Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many 'STA' threads can coexist inside a process?

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 ?

like image 389
Xaqron Avatar asked Dec 24 '10 18:12

Xaqron


3 Answers

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.

like image 52
Ran Avatar answered Nov 11 '22 22:11

Ran


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.

like image 4
fejesjoco Avatar answered Nov 11 '22 22:11

fejesjoco


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.

like image 4
Hans Passant Avatar answered Nov 11 '22 23:11

Hans Passant