简体   繁体   中英

What's the point of using Tasks if I have to create my own STA Threads to run them in parallel?

I've done a lot of reading and watching Microsoft's videos on why I should use Tasks and not threads and it makes sense (I think). But this blog from Microsoft on Parallel Programming with .NET has me confused.

My understanding is by using Tasks I can take better advantage of multiple cores and have these tasks run in parallel. The problem is I'm making calls to native code that instantiates some COM objects so my Tasks have to run on STA threads.

In this article the author says to get a Task to run on an STA thread you have to create the task from an STA thread. He creates ONE STA thread and creates 10 tasks from it, then comments that all the tasks will run sequentially due to creating the tasks from one thread.

Wait... why? If I have to create my own threads to get my Tasks to run in parallel, doesn't that kind of defeat the purpose? And why don't they run in parallel?

What am I missing?

If I have to create my own threads to get my Tasks to run in parallel, doesn't that kind of defeat the purpose? And why don't they run in parallel?

Well the problem specific to your case is that you are interacting with a Single Threaded Apartment (STA) COM object. STA means it is not thread safe.

Most if not all UI COM objects (eg anything in Microsoft Office Ole Automation) are not thread safe either by design or for historical reasons and must be invoked from the thread that created them. All such method calls are sent via the Windows Message Pump hence why they are serialised.

It is no different if you attempted to update your own UI from a worker thread - you can't.

What's the point of using Tasks if I have to create my own STA Threads to run them in parallel?

  1. Well according to that article you are ultimately creating your own task scheduler not just "create my own ... threads" . Custom task schedulers are not a bad thing and TPL allows for this by design

  2. You'll never be able to call STA COM objects in parallel if they all belong to the same process

Conclusion

It seems you are perhaps blaming TPL for this COM STA problem which is slightly unfair. STA thread problems persist whether you avoid TPL entirely and use your own threads; if you attempt to call STA COM objects from say c++; or when using DCOM via networked computers on a LAN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM