使用线程很简单
Thread thread = new Thread(MethodWhichRequiresSTA); thread.SetApartmentState(ApartmentState.STA);如何在WPF应用程序中完成相同的任务? 这是一些代码:
Task.Factory.StartNew ( () => {return "some Text";} ) .ContinueWith(r => AddControlsToGrid(r.Result));我得到一个InvalidOperationException
调用线程必须是STA,因为许多UI组件需要这样做。
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.
最满意答案
您可以使用TaskScheduler.FromCurrentSynchronizationContext方法获取当前同步上下文的TaskScheduler (当您运行WPF应用程序时,这是WPF调度程序)。
然后使用接受TaskScheduler的ContinueWith重载:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(...) .ContinueWith(r => AddControlsToGrid(r.Result), scheduler);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);更多推荐
发布评论