WPF高度并发的跨线程UI访问 [英] WPF Highly-Concurrent Cross-Thread UI Access

查看:112
本文介绍了WPF高度并发的跨线程UI访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我有几个工作的工人,我需要将此反映到UI中.更新进度条,将项目添加到列表等.

In C# I have several workers that do work and I need to reflect this into the UI. Update a progress bar, add items to a list and so on.

第一次尝试这样做,我准备了所有带有锁的东西,以确保在每个给定的时刻只有一个线程访问UI,但是我遇到了异常.因此,我了解到我需要使用 Dispatcher.Invoke 来访问和更改UI元素.将每个UI更改都包含在一个调用中是很麻烦的,但我可以解决.

First time I tried to do this, I prepared everything with locks to make sure only one thread accesses the UI at every given moment but I got an exception. So I learned I need to use the Dispatcher.Invoke to access and change UI elements. It's quite cumbersome to enclose each UI change into an invoke but I can deal with it.

  • 是否需要同步 Dispatcher.Invoke 调用,还是在内部完成?所以我想知道是否需要添加另一层带锁的保护...
  • 在分派器中排队许多更新请求是否会影响性能?因此,如果有多个线程正常工作,并且每个线程都以很小的变化反映到UI中,那么如何向Dispatcher发出许多调用.`会影响性能吗?我应该使用计时器,仅每秒更新一次UI,并在内部对所有UI更改进行排队吗?
  • 有没有更简单的方法可以进行更多内联的跨线程访问...而无需调用?
  • Is it necessary to synchronize the Dispatcher.Invoke calls or is that done internally? So I wonder if I need to add another layer of protection with locks...
  • Does it impact performance having many update requests queued into the dispatcher? So if several threads work and each of them reflects into the UI with a small change, how does issuing many calls to Dispatcher.Invoke` affect performance? Should I use a timer and only update UI once a second and queue all the UI changes internally?
  • Is there an easier way to do cross-thread access more inline... without Invokes?

推荐答案

人脑将无法每秒处理200次更新.它只会减慢您的用户界面,并不会给您带来任何好处.

The human brain won't be able to process 200 updates/sec. It will just slow down your UI and not gain you anything.

相反,使计时器每200ms轮询一次状态.这将足够快(每秒5次更新)而不会引起注意.

Instead, make a timer that polls for status every, say, 200ms. This will be fast enough (5 updates/sec) not to be noticeable.

无需锁定调度程序,它是在内部处理的.但是,您应该将任务专用于计算,而不要通过它们来操作UI.像我所说的那样实现一个计时器,并使用某种标准的跨线程通信方式来从UI线程中检索当前状态.

No need to lock on the dispatcher, it's handled internally. But you should dedicate your tasks to the computations, and not manipulate the UI from them. Implement a timer like I said, and use some standard way of cross-thread communication to retrieve the current status from the UI thread.

这篇关于WPF高度并发的跨线程UI访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆