13
votes

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.

1

1 Answers

16
votes

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.