在多线程应用程序中使用后台工作者
我的查询是关于 BackgroundWorker
的。
我有一个 Windows 窗体应用程序,它启动 10 个新线程。每个线程将从 10 个不同的 Web 服务获取一些信息。我所需要的只是将 Web 服务调用的结果附加到设计模式下的富文本框中。在这种情况下如何利用后台线程?
ArrayList threadList;
for (int idx = 0; idx < 10; ++idx)
{
Thread newth= new Thread(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.
}
非常感谢任何帮助。
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 Thread(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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在工作线程中,您可以通过以下方式更新 Richtextbox:
In worker threads you can update richtextbox in following way:
我不确定使用 BackgroundWorker 是否是您的情况的最佳解决方案。但是,如果您确实使用backgroundWorker,则可以使用相同的 RunWorkerCompleted事件(在主线程上运行)。因此您可以更新该事件的用户界面。
如果您正在寻找backgroundWorker的示例,请查看此处。
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.
我不太了解上下文,但我相信以下内容:
因此解决方案不是使用 BackgroundWorker。相反,您应该使用 BeginInvoke: http:// /msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.begininvoke.aspx
您的问题,正如Hans Passant评论sllev 的回答,可能是您阻塞了 UI 线程出于某种原因,使用 Invoke。
尝试用 BeginInvoke 替换 Invoke。
I don't really understand the context, but I believe the following:
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
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.