How can I create WPF controls in a background thread?

后端 未结 8 869
终归单人心
终归单人心 2021-01-17 15:49

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 :

8条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-17 16:14

    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.

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

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

提交回复
热议问题