在创建后台线程WPF UI的? [英] creating a UI in background thread WPF?

查看:173
本文介绍了在创建后台线程WPF UI的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着以下内容:

var task = new Task(() =>
    {
       for (int i=0; i<10; i++) {
          //Create new Grid HERE
          // Add Table with some dynamic data here..
          // print the above Grid here.
        }

    });

task.ContinueWith((previousTask) =>
    {
        label.Content = printerStatus(); // will return "Out of Paper", "printing", "Paper jam", etc.
    },
    TaskScheduler.FromCurrentSynchronizationContext());

label.Content = "Sending to printer";



它返回以下错误:调用线程必须STA,因为许多UI组件都需要这个..

It returns following error: The calling thread must be STA, because many UI components require this..

当它试图创建一个新的UI对象网格时发生错误。

The error occurs when it tries to create a new UI object Grid.

我怎样才能解决这个问题?让我知道是否有任何其他方式以防万一!

How can i fix this? Let me know if there is any other way arround!

推荐答案

任务使用线程池中的线程,这是在一个MTA。

Tasks use thread pool threads, which are in a MTA.

如果你想有一个后台STA线程,你必须自己创建一个并明确设置的ApartmentState

If you want a background STA thread, you will have to create one yourself and explicitly set the ApartmentState.

Thread t = new Thread( ... );
t.SetApartmentState( ApartmentState.STA );
t.Start();

这篇关于在创建后台线程WPF UI的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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