我是否需要BackgroundWorker?

发布于 2025-01-07 11:41:40 字数 229 浏览 1 评论 0原文

我正在编写某种应用程序,它将向服务器发送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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雨夜星沙 2025-01-14 11:41:40

您确实应该使用 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.

桃扇骨 2025-01-14 11:41:40

但问题是如何在不冻结用户界面的情况下发送请求和处理响应?

您可以使用计时器定期发送请求。如果您需要在请求成功时更新 UI,您可能需要使用 Dispatcher.InvokeControl.Invoke

but the question is how can i send requests and process responses without freezing ui?

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 or Control.Invoke.

淡莣 2025-01-14 11:41:40

您可以使用多种选项在后台执行工作,同时 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文