WPF 4.5中的INotifyDataErrorInfo和异步数据验证

时间:2014-02-05 04:56:43

标签: c# .net wpf asynchronous async-await

是否允许从非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返回值发生变化时,即使返回,也会发生线程   value实现INotifyCollectionChanged

这篇文章似乎来自一个可靠的来源,显然代码已经过测试。

我错过了什么吗?这是一个错误,还是WPF 4.5对此负责,similar to PropertyChanged

1 个答案:

答案 0 :(得分:7)

我认为这是一个错误。然后,我总是在UI线程上提出PropertyChanged;因为即使WPF碰巧处理它,其他MVVM框架也可能没有。

当然,理想情况下,服务是异步的(因为它是I / O绑定的),在这种情况下,也不需要Task.Run。哦,并且示例当前使用async void方法,如果发生任何不幸事件(例如,如果验证服务不可用),则会引发应用程序级错误。

此外,只要您使用用户的输入异步执行某些操作,您就需要考虑有关延迟和错误的用户体验。特别是,我更喜欢一种显示内联忙指示符的解决方案,以便用户知道该字段正在被验证。然后它可以在验证完成时更改为绿色检查或红色x或其他内容。