Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

444
Views
Is CoInitialize() always implicitly called on every .Net Framework / .Net Core thread?

There are those [MTAThread] and [STAThread] attributes which control the apartment threading model for COM in .Net applications, and from my own (very limited) testing, CoInitializeEx() returns 1 (S_FALSE) if called from the main thread of a console C# application.

According to Microsoft documentation, S_FALSE means "The COM library is already initialized on this thread".

What I am wondering is whether there is actually a contractual guarantee in the framework itself that COM is going to be initialized on every .Net (Framework or Core application) thread?

If so, is it also guaranteed that all threads will be initialized with the same (STA or MTA) model?

I am asking this because for DirectShow applications it is crucial that COM is initialized on every thread, and I would like to avoid peppering the code with redundant calls to CoInitializeEx() and CoUnitialize() if those are already implicitly handled by the framework.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The documentation states that threads from the Managed Thread Pool are

in the multithreaded apartment

The documentation for Task.Run() also states that it

Queues the specified work to run on the ThreadPool

(ThreadPool in this case being the Managed Thread Pool.)

Finally, the documentation for class Thread's obsolete ApartmentState property states that

In .NET Framework version 2.0, new threads are initialized as ApartmentState.MTA if their apartment state has not been set before they are started.

That covers pretty much all of the managed ways to create a thread.

You could of course slap an [MTAThread] attribute on your Main() method too, but even that's not necessary because the default for the main entry point is MTA too.

So at the end of the day - unless you're calling any unusual third-party code, you can pretty much be guaranteed that your threads will be MTA.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!