Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...