【发布时间】:2014-03-01 09:26:27
【问题描述】:
是否允许从非 UI 线程触发 ErrorsChanged 事件?我正在看以下文章:
Validating Data in WPF 4.5 Using the INotifyErrorDataError Interface.
特别是,我对此代码片段有疑问:
private async void ValidateUsername(string username)
{
const string propertyKey = "Username";
ICollection<string> validationErrors = null;
/* Call service asynchronously */
bool isValid = await Task<bool>.Run(() =>
{
return _service.ValidateUsername(username, out validationErrors);
})
.ConfigureAwait(false);
if (!isValid)
{
/* Update the collection in the dictionary returned by the GetErrors method */
_validationErrors[propertyKey] = validationErrors;
/* Raise event to tell WPF to execute the GetErrors method */
RaiseErrorsChanged(propertyKey);
}
else if(_validationErrors.ContainsKey(propertyKey))
{
/* Remove all errors for this property */
_validationErrors.Remove(propertyKey);
/* Raise event to tell WPF to execute the GetErrors method */
RaiseErrorsChanged(propertyKey);
}
}
注意 ConfigureAwait(false) 如何在等待 Task<bool>.Run 之后允许池线程上的继续:
这很可能会导致在非 UI 线程上触发 ErrorsChanged 事件。 与 MSDN 相悖:
实现类应在用户界面上引发此事件 每当
GetErrors返回值改变时线程,即使返回 值实现INotifyCollectionChanged。
这篇文章似乎来自可靠的来源,显然代码已经过测试。
我错过了什么吗?这是一个错误,还是 WPF 4.5 解决了这个问题,similar to PropertyChanged?
【问题讨论】:
标签: c# .net wpf asynchronous async-await