gpt4 book ai didi

c# - 使用 Dispatcher 切换到 UI 线程的正确语法

转载 作者:太空宇宙 更新时间:2023-11-03 19:09:27 25 4
gpt4 key购买 nike

有什么区别

Dispatcher.CurrentDispatcher.Invoke(somemethod);

Application.Current.Dispatcher.Invoke(somemethod);

当我使用第一个方法时,某些方法的执行速度比第二个方法快得多。我使用秒表并测量经过的毫秒数。我使用此方法根据来自外部线程的一些数据更新一些 UI 控件。

最佳答案

Dispatcher.CurrentDispatcher 将为您提供与调用此方法的当前线程关联的调度程序

Application.Current.Dispatcher 将使与 UI 线程关联的调度程序(假设您的 App 是从 UI 线程启动的)。


本质上,如果您从后台线程调用委托(delegate)并尝试从中更新 UI 组件,请说

textBlock.Text = "Test";

第一种方法会失败,因为它会在后台线程调度程序上调用委托(delegate),并且只能从 UI 线程修改 UI 组件。

第二种方法可行,因为它将在 UI 线程上委派任务。


When I use the first one the execution of somemethod is way faster than the second one.I used stopwatch and measured elapsed milliseconds.I use this method to update some UI controls based on some data coming from external thread.

如果第一种方法适合您,那么根本不需要使用 Dispatcher,因为这意味着您已经在 UI 线程上

并且您需要发布样本数据以观察时间,以便对其进行验证。

关于c# - 使用 Dispatcher 切换到 UI 线程的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22007801/

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