Add controls to a StackPanel in a BackgroundWorker or async Task called from another BackgroundWorker

痞子三分冷 提交于 2019-12-14 03:36:54

问题


I'm coding an IRC Client, using Meebey SmartIrc4Net.

By using a BackgroundWorker, i listen to all IRC events by the .Listen() method provided by the class.

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.

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.

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.

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

I have used bgWorkers and async/await and tasks since my app uses .Net Framework 4.5, both to no avail.

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.

Thanks in advance.


回答1:


You cannot create controls from any thread except for the UI thread.

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.



来源:https://stackoverflow.com/questions/33349224/add-controls-to-a-stackpanel-in-a-backgroundworker-or-async-task-called-from-ano

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!