是否有其他方法可以在 WPF 中使用后台工作人员?
我是 WPF 的初学者,在我的应用程序中,我需要执行一系列初始化步骤,这些步骤需要 10-15 秒才能完成,在此期间我的 UI 变得无响应。
我昨天使用了后台工作程序,但它没有更新我的窗口,事实上它被冻结了。不确定,但也许它不起作用,因为该控件仅适用于 Windows 窗体。
更新:
如果不是太麻烦,你能给我一个使用替代方案的例子吗?就我而言,程序将从数据库中快速获取一些值。
I am a beginner with WPF, in my application I need to perform a series of Initialization steps, these take 10-15 seconds to complete during which my UI becomes unresponsive.
I was using yesterday the background worker but it didn't update my window, in fact it was frozen. Not sure, but maybe it didn't work because this control is only for Windows Forms.
UPDATE:
If not too much trouble, can you post me an example to use the alternative? For my case, the program will get some values from a database in a blucle.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调度程序。
调度程序为特定线程维护一个按优先级排列的工作项队列。这可能会帮助您更新 UI。如果您有很多与 UI 相关的初始化,那么即使这也无法为您提供太大帮助。
实际上,Dispatcher 并不总是 BackgroundWorker 的替代品。最佳实践是根据您的要求选择更合适的。例如,如果您希望在不排队的情况下执行某些操作,BackgroundWorker 就是解决方案。另一方面,如果排队不是问题,那么调度程序是一个替代方案。例如,Dispatcher 正在使用拼写检查器和语法突出显示功能。
笔记 :
请参阅此主题了解更多信息。
Dispatcher.
The Dispatcher maintains a prioritized queue of work items for a specific thread. This might help you for updating your UI. If you have a lot of UI related initializations even this won't be able to help you much.
Dispatcher is not always an alternative to BackgroundWorker actually. The best practice is to select the more appropriate one as per your requirement. For example if you want something to execute without queuing BackgroundWorker is the solution. On the other hand if queuing is not a problem then Dispatcher is an alternative. For example, Dispatcher is using in Spell checkers and syntax highlighting functionality.
NOTE :
See this thread for more information.
您还可以使用线程池对项目进行排队并运行类似的任务,但要小心,如果您的任务完成后需要更新 UI,则必须将数据封送回 UI 线程。
You could also queue items up with the thread pool and run the tasks like that, but be careful, if your tasks need to update the UI when they are finished you will have to marshal the data back to the UI thread.
可以使用异步委托。
http://msdn.microsoft.com/en-us/library/ms228963.aspx
只需确保您是否正在执行任何与 UI 相关的更新,请使用:
这里是一个简单的示例:
取自此处:
http://blog.clauskonrad.net/2009/03/wpf-invokerequired-dispatchercheckacces .html
One could use asynchronous delegates.
http://msdn.microsoft.com/en-us/library/ms228963.aspx
Just make sure if you are doing any UI related updates use:
Here a simple example:
Taken from here:
http://blog.clauskonrad.net/2009/03/wpf-invokerequired-dispatchercheckacces.html