我阅读了许多关于绑定和GUI控件线程亲和力的帖子、文章等。有些帖子中,人们不想使用Dispatcher
。
我还有一个同事在他的代码中避免使用Dispatcher
。我问他原因,但他的回答并没有令我满意。他说,他不喜欢这种隐藏在类中的“魔法”。
好吧,我是以下这个类的粉丝。
public class BindingBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Dispatcher Dispatcher
{
#if SILVERLIGHT
get { return Deployment.Current.Dispatcher; }
#else
get { return Application.Current.Dispatcher; }
#endif
}
protected void RaisePropertyChanged<T>(Expression<Func<T>> expr)
{
var memberExpr = (MemberExpression)expr.Body;
string property = memberExpr.Member.Name;
var propertyChanged = PropertyChanged;
if (propertyChanged == null) return;
if (Dispatcher.CheckAccess())
propertyChanged.Invoke(this, new PropertyChangedEventArgs(property));
else
Dispatcher.BeginInvoke(() => RaisePropertyChanged(expr));
}
}
这里有一个问题。是否有任何原因,使一些人不想使用这样的类?也许我需要重新考虑这种方法。
你必须承认,有一件奇怪的事情。
Dispatcher.CheckAccess()
在Intellisense中被排除了。也许由于这个事实它们有点可怕。问候
编辑:
好的,再举个例子。考虑一个复杂的对象。以集合为例可能不是最好的主意。
public class ExampleVm : BindingBase
{
private BigFatObject _someData;
public BigFatObject SomeData
{
get { return _someData; }
set
{
_someData = value;
RaisePropertyChanged(() => SomeData);
}
}
public ExampleVm()
{
new Action(LoadSomeData).BeginInvoke(null, null); //I know - it's quick and dirty
}
private void LoadSomeData()
{
// loading some data from somewhere ...
// result is of type BigFatObject
SomeData = result; // This would not work without the Dispatcher, would it?
}
}
Dispatcher
来修改集合,但不是普通属性(即您不必在UI线程上引发INotifyPropertyChanged.PropertyChanged'
事件,但您必须在UI线程上引发INotifyCollectionChanged.CollectionChanged
)。 - Pavlo Glazkov