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

nos*_*tio 10 .net c# wpf asynchronous async-await

是否允许ErrorsChanged从非UI线程触发事件?我正在看以下文章:

使用INotifyErrorDataError接口验证WPF 4.5中的数据.

特别是,我有一个关于此代码片段的问题:

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);
    }
} 
Run Code Online (Sandbox Code Playgroud)

注意如何ConfigureAwait(false)在等待之后允许在池线程上继续Task<bool>.Run:

这很可能会导致ErrorsChanged在非UI线程上触发事件.这与MSDN相反:

每当GetErrors返回值发生更改时,实现类都应在用户界面线程上引发此事件,即使返回值实现也是如此INotifyCollectionChanged.

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

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

Ste*_*ary 8

我认为这是一个错误.然后,我也总是提高PropertyChangedUI线程; 因为即使WPF碰巧处理它,其他MVVM框架也可能不会.

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

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