Using backgroundworker in a multithreaded application
My query is about BackgroundWorker
.
I have a windows forms application which starts 10 new threads. Each thread will get some info from 10 different web services. All I need is to append the result from web service call in a rich text box placed in the design mode. How can I make use of background thread in this scenario?
ArrayList threadList;
for (int idx = 0; idx < 10; ++idx)
{
Thread newth= new Thre开发者_Python百科ad(new ParameterizedThreadStart(CallWS));
threadList.Add(newth);
}
for (int idx = 0; idx < 10; ++idx)
{
Thread newth= new Thread(new ParameterizedThreadStart(CallWS));
newth.Start(something);
}
for (int idx = 0; idx < 10; ++idx)
{
//Cast form arraylist and join all threads.
}
private void CallWS(object param)
{
// Calling WS
// got the response.
// what should I do to append this to rich text box using background worker.
}
Any help much appreciated.
In worker threads you can update richtextbox in following way:
private void CallWS(object param)
{
string updatedText = ..
// build a text
this.Invoke((MethodInvoker)delegate {
// will be executed on UI thread
richTextBox.Text = updatedText;
});
}
I am not sure whether using BackgroundWorker is the best solution in your case. However, if you do use backgroundWorker, you could use the same RunWorkerCompleted event (which is run on the main thread) for all the BackgroundWorkers. So you could update your UI on that event.
If you are looking for an example for backgroundWorker look at here.
I don't really understand the context, but I believe the following:
- You are working with Windows.Forms
- You have multiple threads
- Each thread wants to execute code (appending text) in the UI thread
So the solution is not using a BackgroundWorker. Instead, you should use BeginInvoke: http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.begininvoke.aspx
RichTextBox.BeginInvoke Method
Executes a delegate asynchronously on the thread that the control's underlying handle was created on.
Your problem, as Hans Passant commented on sllev's answer, could be you're blocking the UI thread for some reason, using Invoke.
Try replacing Invoke with BeginInvoke.
精彩评论