Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/await, ThreadPool and SetApartmentState

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.

like image 458
avo Avatar asked Oct 29 '13 02:10

avo


1 Answers

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.

like image 171
Stephen Cleary Avatar answered Oct 21 '22 21:10

Stephen Cleary