I managed to write a relatively large WinForms application in C# that functions correctly without the [STAThread]
attribute on the Main()
method.
To accomplish this I had to override a lot of WinForms functionality (such as using a custom BeginInvoke
and Invoke
functions), use a custom message loop instead of Application.Run
, use a custom file dialog instead of OpenFileDialog
and SaveFileDialog
, and use WM_DROPFILES for drag-and-drop instead of the WinForms out-of-the-box OLE approach. This is all "for science".
Now I want to test for any possible performance impact of omitting the STAThreadAttribute from all GUI threads. I do not possess deep enough knowledge of the COM configuration used internally by the Control class to be able to predict such impact. Speed of execution probably depends on which thread is calling the internal COM object of the Control
.
Admittedly, I am having trouble coming up with a benchmark that would test for performance impact pertaining to [STAThread]
, because I am unsure of which functions/operations would be affected by such a change (specifically related to the Control
class).
What should I look for exactly? Which operations/methods from the Control
class should I expect to run faster/slower by omitting [STAThread]
, if any?
Addendum: The rationale is that I am slowly migrating my application to use a custom windowing system (for portability reasons, mainly for using Mono on Linux, whose WinForms implementation is not complete), so I had to override a lot of functionality myself anyway. It was merely a coincidence that I noticed that I had overridden so much functionality that I could omit [STAThread] and everything would still work as expected.
I expect a change in performance due to COM marshaling calls from the ThreadPool
(which is configured as MTA), and the GUI thread (which by default should be configured as STA). Calls from the ThreadPool
to the GUI thread would need to be marshalled due to them being configured in different thread apartments, which introduces a synchronization overhead. By leaving the GUI thread as MTA, the marshalling should be reduced, hence possibly faster execution of function calls. I would like to test this claim pragmatically.