问题
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