我可以安全地绑定到多线程应用程序上的数据吗? [英] Can I safely bind to data on multi-threaded applications?
问题描述
我试图解决一个经典的问题 -
我有一个多线程应用程序,运行一些
处理器密集型计算,带有一个GUI界面。
I'm trying to solve a classic problem - I have a multi-threaded application which runs some processor-intensive calculations, with a GUI interface.
每当一个线程完成一个任务,我想要
更新表上的状态
Every time one of the threads has completed a task, I'd like to update a status on a table
taskID |状态
taskID | status
我以下列方式使用DataGridView和BindingList:
I use DataGridView and BindingList in the following way:
BindingList<Task> tasks;
dataGridView.DataSource = tasks
public class Task : INotifyPropertyChanged
{
ID{get;}
Status{get;set;}
}
后台线程可以安全地更新任务的状态吗?
和更改将以GUI中的正确顺序显示?
Can a background thread safely update a task's status? and changes will be seen in the correct order in the GUI?
第二个问题:
什么时候需要调用PropertyChanged?
我试着运行和没有通话,似乎没有打扰..
Second Question: When do I need to call to PropertyChanged? I tried running with and without the call, didn't seem to bother..
第三个问题:
我在MSDN上看到dataGridView使用BindingSource
作为DataGridView.DataSource和BindingList之间的调解器
这是真的有必要吗?
Third Question: I've seen on MSDN that dataGridView uses BindingSource as a mediator between DataGridView.DataSource and BindingList Is this really necessary?
推荐答案
1 - 否。在更新数据绑定属性之前,背景任务必须与UI线程同步。这可以通过使用计划到 TaskScheduler.FromCurrentSynchronizationContext
的任务
完成。
1 - No. Background tasks must synchronize to the UI thread before updating databound properties. This can be done by using a Task
scheduled to TaskScheduler.FromCurrentSynchronizationContext
.
如果你还没有在.NET 4.0(例如,任务
不可用),那么这取决于你的任务的运作方式:a使用完成概念的任务可以使用 BackgroundWorker
,无限期运行的任务可以使用 SynchronizationContext.Post
。
If you're not on .NET 4.0 yet (e.g., Task
isn't available), then it depends on how your "tasks" operate: a task with the concept of "completion" can use BackgroundWorker
, and a task that runs indefinitely can use SynchronizationContext.Post
.
2 - PropertyChanged
被绑定用于更新其显示。不知道为什么它对你没有调用它...
2 - PropertyChanged
is used by the binding to update its display. Not sure why it worked for you without calling it...
3 - BindingSource
提供各种功能;见什么是绑定源,为什么需要它?
3 - BindingSource
provides various functionality; see What Is a BindingSource and Why Do I Need It?
BTW:欢迎您在SO上提出多个问题。这个问题应该是三个。
BTW: you're welcome to ask more than one question on SO. This one question should really be three.
这篇关于我可以安全地绑定到多线程应用程序上的数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!