在后台线程中创建元素,然后添加到主界面 [英] Create element in background thread an then add to main-interface
问题描述
我在WPF中有线程问题.我想创建一个复杂的用户界面,然后将其添加到主窗口中.在创建这个复杂的用户界面时,我想在主窗口中显示一个进度栏.我认为这只能通过线程来实现.但有一个问题.无法将创建的元素添加到主窗口,因为它是在单独的线程中创建的. 有人知道是否有可能将在后台线程中创建的UIElement转移到主线程中. 如果我以一种简单的方式尝试,它表示无法访问该对象,因为该对象位于单独的线程中.我已经使进度条线程安全了.
i have a problem with threading in WPF. I want to have created a complex user interface and then i want to add it to my main-window. While this complex user interface is creating i want to show a progress bar in my main window. I think this only could be made with threads. But there is a problem. The created element can't be added to main window because it is created in a separate thread. Do anybody know if there is a possibility to transfer UIElements that are created in a background-thread to the main-thread. If i try in a simple way it says that the object can't be accessed because it is in a separate thread. I have already made my progress-bar thread safe.
我希望下面的示例能更好地解释我的意图.
I hope following example explain a bit better what i want to to.
StackPanel tcForm = new StackPanel();
Semaphore loadedSema = new Semaphore(0,1);
Thread thread = new Thread(new ThreadStart(delegate(){
//Formular should be created in background
tcForm.Children.Add(new Formular());
ProgressBar.AddProgress();
//...other things
loadedSema.Release();
}));
thread.start();
loadedSema.WaitOne();
new Formular()
运行很长时间,所以我考虑过在后台创建.
new Formular()
runs a very long time, so i thought about creating in background.
将Formular
添加到变量然后再将其添加到主线程也是不可能的.
It is also impossible to add Formular
to a variable and then add it main thread.
//this is also impossible
//in background-thread
form = new Formular
//in main-thread
tcForm.Children.Add(form);
我希望有办法. 如果有一些建议,那会很好,
I hope that there is a way to this. Would be nice if there are some advices,
谢谢马丁
推荐答案
您应该使用 编辑
您可以在分派之前创建Fromular()对象,如果它能长时间工作的话
EDIT
You can create Fromular() object before dispatching, if it is working long
var f = new Formular();
this.Dispatcher.Invoke(delegate{ tcForm.Children.Add(f);
ProgressBar.AddProgress();};)
这篇关于在后台线程中创建元素,然后添加到主界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!