I'd like to use await Task.Run(DoWork)
, to do some repetitive single-threaded computational work on ThreadPool. The problem is, I need to use STA COM objects inside DoWork
, so I guess I cannot use ThreadPool because I cannot alter the apartment state of a pool thread.
How can I still use async
/await
in this scenario? Creating my own pool of STA threads with a custom task scheduler sounds like an excessive work.
Stephen Toub has already written an StaTaskScheduler
(archive); I recommend you use that.
You can then construct a TaskFactory
using that TaskScheduler
. There is no equivalent to Task.Run
on the TaskFactory
type but you can easily create one using StartNew
and Unwrap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With