如何创建运行 STA 线程的任务 (TPL)? [英] How to create a task (TPL) running a STA thread?

查看:26
本文介绍了如何创建运行 STA 线程的任务 (TPL)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用线程非常简单

 Thread thread = new Thread(MethodWhichRequiresSTA);
 thread.SetApartmentState(ApartmentState.STA);  

如何在 WPF 应用程序中使用任务完成相同的任务?这是一些代码:

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));  

我收到一个 InvalidOperationException

I'm getting an InvalidOperationException with

调用线程必须是 STA,因为很多 UI 组件都需要这个.

The calling thread must be STA, because many UI components require this.

推荐答案

您可以使用 TaskScheduler.FromCurrentSynchronizationContext 方法 获取TaskScheduler 用于当前同步上下文(当您运行 WPF 应用程序时,它是 WPF 调度程序).

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).

然后使用接受 TaskScheduler 的 ContinueWith 重载:>

Then use the ContinueWith overload that accepts a TaskScheduler:

var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

Task.Factory.StartNew(...)
            .ContinueWith(r => AddControlsToGrid(r.Result), scheduler);

这篇关于如何创建运行 STA 线程的任务 (TPL)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆