如何创建任务(TPL)运行的STA线程? [英] How to create a task (TPL) running a STA thread?
问题描述
使用线程是pretty简单
线程线程=新主题(MethodWhichRequiresSTA);
thread.SetApartmentState(ApartmentState.STA);
如何完成任务用在WPF应用程序一样吗?下面是一些code:
Task.Factory.StartNew
(
()=>
{返回一些文本;}
)
.ContinueWith(R => AddControlsToGrid(r.Result));
我得到一个InvalidOperationException以
调用线程必须STA,因为许多UI组件都需要这一点。
块引用>解决方案您可以使用TaskScheduler.FromCurrentSynchronizationContext方法获得的TaskScheduler 当前同步上下文(这是WPF调度当你运行一个WPF应用程序)。
然后使用 ContinueWith 重载接受的TaskScheduler:
VAR调度= TaskScheduler.FromCurrentSynchronizationContext();Task.Factory.StartNew(...)
.ContinueWith(R = GT; AddControlsToGrid(r.Result),调度程序);Using Thread is pretty straightforward
Thread thread = new Thread(MethodWhichRequiresSTA); thread.SetApartmentState(ApartmentState.STA);
How to accomplish the same using Tasks in a WPF application? Here is some code:
Task.Factory.StartNew ( () => {return "some Text";} ) .ContinueWith(r => AddControlsToGrid(r.Result));
I'm getting an InvalidOperationException with
The calling thread must be STA, because many UI components require this.
解决方案You can use the TaskScheduler.FromCurrentSynchronizationContext Method to get a TaskScheduler for the current synchronization context (which is the WPF dispatcher when you're running a WPF application).
Then use the ContinueWith overload that accepts a TaskScheduler:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(...) .ContinueWith(r => AddControlsToGrid(r.Result), scheduler);
这篇关于如何创建任务(TPL)运行的STA线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!