我是否需要BackgroundWorker?
我正在编写某种应用程序,它将向服务器发送http请求。我的应用程序将通过计时器以一定的间隔发送请求。例如,我需要发送 1 种类型的请求,时间间隔为 2 秒,第二种类型的请求 - 10 秒,依此类推。 我知道最好有一个调度程序来推动我的请求。但问题是如何在不冻结用户界面的情况下发送请求并处理响应?
ps 现在我有 MyAdapter 类,它封装了请求和响应的所有工作,以及 MyScheduler 类,它通过计时器发送请求。
i'm writing some kind of application that will send http requests to server. My app will send requests with some interval by timer. for example, i need to send 1 type of requests with time interval 2 seconds, 2nd type of requests - 10 seconds and so on.
i understand that it is better to have one scheduler that will push my requests. but the question is how can i send requests and process responses without freezing ui?
p.s. right now i have class MyAdapter, which encapsulates all work with requests and responses, and class MyScheduler, which sends requests by timer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确实应该使用 BackGroundWorker,如果您需要同时更新 UI,则可以使用 Dispatcher.Invoke() 方法。
You should indeed then use a BackGroundWorker and if you need to update the UI in the meantime, you can use the Dispatcher.Invoke() method.
您可以使用计时器定期发送请求。如果您需要在请求成功时更新 UI,您可能需要使用
Dispatcher.Invoke
或Control.Invoke
。You could use timers to send your requests at regular intervals. If you need to update your UI when the request succeeds you might need to use the
Dispatcher.Invoke
orControl.Invoke
.您可以使用多种选项在后台执行工作,同时 UI 保持响应:
旧但可靠:
BackgroundWorker
已经在 .net Framework 中存在很长时间了,并且可以完美地满足您的要求。 很多示例可以在此网站和其他地方找到。最先进的技术:自 .NET 4 起可用的
Task
类是 被认为是对BackgroundWorker的改进。全新:
异步 扩展
是执行“后台操作”的新方法。无需多线程和手动同步,一切“正常工作”。不过,目前还处于“社区预览”阶段。
You have a variety of options for performing work in the background while the UI stays responsive:
Old, but reliable:
BackgroundWorker
has been around the .net Framework for a long time and would work perfectly fine for your requirements. Lots of examples can be found on this site and elsewhere.State of the art: The
Task
class, available since .NET 4, is considered to be an improvement over BackgroundWorker.Brand new: The
Async
extensions are the new way to do "background stuff". No need for multi-threading and manual synchronization, everything "just works". However, this is just at "community preview" stage at the moment.