我怎样才能在后台线程创建WPF控件? [英] How can I create WPF controls in a background thread?

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

问题描述

我有创建后台线程来进行一些操作方法。在此背景下线程创建的对象。但是这个对象,而在运行时创建给我一个例外:

I have method which create background thread to make some action. In this background thread I create object. But this object while creating in runtime give me an exception :

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

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

我知道,我必须使用调度,使反映的东西UI。但在这种情况下,我只是创建一个对象,不iteract与UI。这是我的代码:

I know that I must use Dispatcher to make reflect something to UI. But in this case I just create an object and dont iteract with UI. This is my code:

    public void SomeMethod()
      {
         BackgroundWorker worker = new BackgroundWorker();
         worker.DoWork += new DoWorkEventHandler(Background_Method);
         worker.RunWorkerAsync();
      }

   void Background_Method(object sender, DoWorkEventArgs e)
      {
         TreeView tv = new TreeView();
      }



我怎么能在后台创建线程对象?

How can I create objects in background thread?

我使用WPF应用程序

推荐答案

TreeView控件是一个UI控件。您只能创建和操作UI线程UI控件,所以你想做什么是不可能的。

TreeView is a UI control. You can only create and manipulate UI controls on a UI thread, so what you're trying to do is not possible.

您想要做的是做所有的耗时在后台线程上的工作,然后回调到UI线程操纵UI。这其实是很容易的:

What you want to do is do all of the time-consuming work on the background thread, and then "call back" to the UI thread to manipulate the UI. This is actually quite easy:

void Background_Method(object sender, DoWorkEventArgs e)
{
    // ... time consuming stuff...

    // call back to the window to do the UI-manipulation
    this.BeginInvoke(new MethodInvoker(delegate {
        TreeView tv = new TreeView();
        // etc, manipulate
    }));
}



我可能会得到语法错误的的BeginInvoke (这是把我的头顶部),但你去那里反正...

I may have got the syntax wrong for BeginInvoke (it's off the top of my head), but there you go anyway...

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

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