问题描述
我正在使用Meebey SmartIrc4Net编码IRC客户端.
I'm coding an IRC Client, using Meebey SmartIrc4Net.
通过使用BackgroundWorker,我通过类提供的.Listen()方法收听所有IRC事件.
By using a BackgroundWorker, i listen to all IRC events by the .Listen() method provided by the class.
我使用一种方法处理一个OnJoin事件,该方法通过产生另一个BackgroundWorker并轮询其中的数据来获取通道的用户列表.
There's an OnJoin event which i handle with a method, this method gets the user list of the channel by spawning another BackgroundWorker and polling for the data in it.
因此,现在我有一个Main线程,一个irc事件bgWorker(据我所知是Main线程的子级)和一个用户列表bgWorker.
So now i have a Main thread, an irc event bgWorker which to my knowledge is a child of the Main thread, and a user list bgWorker.
问题是我无法在任何bgWorkers中创建UI元素,例如,如果我要将按钮添加到StackPanel中,则无法在bgWorkers工作方法内声明按钮,或者即使我使用reportProgress方法也是如此似乎正在向第一个bgWorker报告,而不是向主线程报告.
The problem is that i cannot create UI elements in any of the bgWorkers, for example, if i want to add buttons to a StackPanel i cannot declare the buttons inside the bgWorkers work methods or even if i use a reportProgress method as it seems to be reporting to the first bgWorker and not to the main thread.
自从我的应用程序使用.Net Framework 4.5以来,我一直使用bgWorkers和async/await和任务,但都无济于事.
I have used bgWorkers and async/await and tasks since my app uses .Net Framework 4.5, both to no avail.
这与最常见的方案不同,在最常见的方案中,您将bgWorker中的控件添加到主线程中,我有三个线程,并且我试图从主线程的子级中的子级中添加控件,并且解决方案仅在只有一个bgWorker和主线程的情况下才有用.
This is different to the most common scenario where you add controls from a bgWorker into the main thread, i have three threads, and i'm trying to add controls from the child of the child of the main thread, and the suggested solutions are only useful when there's a single bgWorker and the main thread.
谢谢.
推荐答案
您不能通过UI线程以外的任何线程创建控件.
You cannot create controls from any thread except for the UI thread.
要在UI线程上运行代码,可以使用Dispatcher.BeginInvoke,您可以在启动后台进程之前,在任何UI元素上(在Dispatcher属性中)或在UI线程中使用statis Dispatcher.CurrentDispatcher属性来查找调度程序.
To run code on the UI thread you can use Dispatcher.BeginInvoke, you can find the dispatcher on any UI element (in the Dispatcher property) or using the statis Dispatcher.CurrentDispatcher property from the UI thread before starting the background process.
这篇关于将控件添加到BackgroundWorker中的StackPanel或从另一个BackgroundWorker中调用的异步任务中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!