gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:10:07 24 4
gpt4 key购买 nike

是否允许开火 ErrorsChanged 来自非 UI 线程的事件?我正在查看以下文章:

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)用于在 await Task<bool>.Run 之后允许在池线程上继续:

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

The implementing class should raise this event on the user interface thread whenever the GetErrors return value changes, even if the return value implements INotifyCollectionChanged.

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

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

最佳答案

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

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

此外,无论何时您做一些与用户输入异步的事情,您确实需要考虑延迟和错误方面的用户体验。特别是,我更喜欢显示内联忙碌指示器或其他内容的解决方案,以便用户知道该字段正在验证中。然后,当验证完成时,它可以变为绿色勾号或红色 x 或其他内容。

关于c# - WPF 4.5 中的 INotifyDataErrorInfo 和异步数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com