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

编程入门 行业动态 更新时间:2024-10-10 17:33:34
如何创建一个运行STA线程的任务(TPL)?(How to create a task (TPL) running a STA thread?)

使用线程很简单

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

更多推荐

本文发布于:2023-04-29 03:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334423.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   创建一个   STA   TPL   thread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!