在 Silverlight 中调用 Dispatcher.CheckAccess() 是一种好的形式吗?
我想知道以下代码是否会带来任何性能提升:
if (Deployment.Current.Dispatcher.CheckAccess())
{
DoUIWork();
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
DoUIWork());
}
Dispatcher 是否足够智能,可以在不必要的情况下短路对 UI 线程的调度?
I wonder if the following code buys any performance gains:
if (Deployment.Current.Dispatcher.CheckAccess())
{
DoUIWork();
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
DoUIWork());
}
Is the Dispatcher smart enough to short circuit a dispatch to the UI thread if its unnecessary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与检查相比,我无法确定调度程序在从 UI 线程调度到自身时是否执行了任何昂贵的操作。但是 UI 线程中的 BeginInvoke 的行为可能与直接执行操作不同,因为它至少被放入队列中而不是立即调用。如果事后直接有代码,您可以区分这与删除条件语句之间的区别。
当然值得了解控制流,足以知道差异是否不重要。
I couldn't say whether the dispatcher does anything expensive when dispatching from the UI thread to itself, compared with the check. But BeginInvoke from the UI thread may behave differently from executing the operation directly, as it's at least put on the queue rather than invoked immediately. You could tell the difference between this and removing the conditional statement if you had code directly afterwards.
Certainly worth being aware of the control flow, enough to know if the difference doesn't matter.
如果它与标准 Windows SynchronizationContext 类似(很可能是),那么这两个选项就不一样。在处理任何现有消息的当前执行后,BeginInvoke 基本上会将要由调度程序消息泵执行的方法排队。
在您的示例中,如果您要使用 Invoke 而不是 BeginInvoke,则这两个选项是相同的。
If it is anything like standard Windows SynchronizationContext (and it probably is) then the two options are not the same. BeginInvoke will basicaly queue up the method to be executed by the dispatcher message pump after the current execution of any existing message has been processed.
In your example the two options be the same if you were to use Invoke instead of BeginInvoke.