gpt4 book ai didi

c# - 在 WPF 中是否有使用后台 worker 的替代方法?

转载 作者:太空狗 更新时间:2023-10-29 21:36:04 26 4
gpt4 key购买 nike

我是 WPF 的初学者,我需要在我的应用程序中执行一系列初始化步骤,这些步骤需要 10-15 秒才能完成,在此期间我的 UI 变得无响应。

我昨天使用了后台工作程序,但它没有更新我的窗口,事实上它被卡住了。不确定,但也许它不起作用,因为此控件仅适用于 Windows 窗体。

更新:

如果不太麻烦,你能给我发一个使用替代方法的例子吗?就我而言,该程序将从一个 blucle 中的数据库中获取一些值。

最佳答案

Dispatcher .Dispatcher 为特定线程维护工作项的优先级队列。这可能会帮助您更新 UI。如果您有很多与 UI 相关的初始化,即使这对您也无济于事。

实际上,Dispatcher 并不总是 BackgroundWorker 的替代品。最佳做法是根据您的要求选择更合适的。例如,如果您希望在不排队的情况下执行某些操作,BackgroundWorker 就是解决方案。另一方面,如果排队不是问题,那么 Dispatcher 是一个替代方案。例如,Dispatcher 正在使用拼写检查器和语法高亮功能。

WPF Thread Model

All WPF applications start out with two important threads, one for rendering and one for managing the user interface. The rendering thread is a hidden thread that runs in the background, so the only thread that you ordinarily deal with is the UI thread. WPF requires that most of its objects be tied to the UI thread. This is known as thread affinity, meaning you can only use a WPF object on the thread on which it was created. Using it on other threads will cause a runtime exception to be thrown. Note that the WPF threading model interoperates well with Win32®-based APIs. This means that WPF can host or be hosted by any HWND-based API (Windows Forms, Visual Basic®, MFC, or even Win32).

The thread affinity is handled by the Dispatcher class, a prioritized message loop for WPF applications. Typically your WPF projects have a single Dispatcher object (and therefore a single UI thread) that all user interface work is channeled through.

注意:

The main difference between the Dispatcher and other threading methods is that the Dispatcher is not actually multi-threaded. The Dispatcher governs the controls, which need a single thread to function properly; the BeginInvoke method of the Dispatcher queues events for later execution (depending on priority etc.), but still on the same thread.

参见 this线程以获取更多信息。

关于c# - 在 WPF 中是否有使用后台 worker 的替代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7005193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com