[英]Async/await, ThreadPool and SetApartmentState
I'd like to use await Task.Run(DoWork)
, to do some repetitive single-threaded computational work on ThreadPool.我想使用await Task.Run(DoWork)
在 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.问题是,我需要在DoWork
使用 STA COM 对象,所以我想我不能使用 ThreadPool 因为我不能改变池线程的单元状态。
How can I still use async
/ await
in this scenario?在这种情况下,我如何仍然使用async
/ await
? Creating my own pool of STA threads with a custom task scheduler sounds like an excessive work.使用自定义任务调度程序创建我自己的 STA 线程池听起来像是一项繁重的工作。
Stephen Toub has already written an StaTaskScheduler
( archive ) ; Stephen Toub 已经编写了一个StaTaskScheduler
(存档) ; I recommend you use that.我建议你使用那个。
You can then construct a TaskFactory
using that TaskScheduler
.然后,您可以使用该TaskScheduler
构造一个TaskFactory
。 There is no equivalent to Task.Run
on the TaskFactory
type but you can easily create one using StartNew
and Unwrap
. TaskFactory
类型上没有与Task.Run
等效的方法,但您可以使用StartNew
和Unwrap
轻松创建一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.