【问题标题】:INotifyDataErrorInfo and asynchronous data validation in WPF 4.5WPF 4.5 中的 INotifyDataErrorInfo 和异步数据验证
【发布时间】: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&lt;bool&gt;.Run 之后允许池线程上的继续:

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

实现类应在用户界面上引发此事件 每当GetErrors 返回值改变时线程,即使返回 值实现INotifyCollectionChanged

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

我错过了什么吗?这是一个错误,还是 WPF 4.5 解决了这个问题,similar to PropertyChanged

【问题讨论】:

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


    【解决方案1】:

    我认为这是一个错误。再说一次,我也总是在 UI 线程上提出PropertyChanged;因为即使 WPF 碰巧可以处理它,其他 MVVM 框架也可能不会。

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

    此外,每当您执行与用户输入异步的操作时,您确实需要考虑有关延迟和错误的用户体验。特别是,我更喜欢显示内联繁忙指示器或其他内容的解决方案,以便用户知道该字段正在被验证。然后它可以在验证完成时变为绿色检查或红色 x 或其他东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 2018-04-08
      • 2015-02-28
      • 2021-01-31
      • 1970-01-01
      相关资源
      最近更新 更多