STAThread and Memory Issues

15. February 2012 15:39 by Mrojas in   //  Tags: , , , , , ,   //   Comments (0)

VB6 Application where STAThread. And that is the reason that Winforms applications are
by default STAThread. Using MTAThread causes problems with some ActiveX Controls.

However STAThread has a nasty implication
"inside a STA thread, the finalizer thread must reenter the STA thread in order to finalize the component.
If the STA is blocked and isn't pumping, the finalizer has to wait in line until it does"

This can then cause leaks of components affecting the memory use.

"To get around this issue, you have some options (from best to worst), e.g.:"

1) Create your components in an MTA. ... Unless you have an explicit reason to use an STA, you shouldn't. I realize that Visual Studio adds these to some entrypoints automatically for you.
For example, most GUI applications have to start life inside an STA, e.g. WinForms, but Console applications"  or services "certainly do not."

"2) Deterministically release your resources. If you are using components which implement IDisposable, wrap them in
a C# 'using' statement or call Dispose() on them explicitly when you're done.
RCW's done have Dispose on them. You can consider doing a Marshal.ReleaseComObject on them directly,
but realize that this can cause problems if you're not really done using the COM object."

"3) Use another form of blocking to prevent the primary thread from exiting."

"Chris Brumme writes about this" (COM Apartments)
" at; caution: that's a fairly lengthy post"