异步 IDataErrorInfo - WPF
Async IDataErrorInfo - WPF
当我想异步使用 IDataErrorInfo (.NET 4.0) 时遇到问题。此代码完美运行。
EditViewModel.cs
public class EditViewModel : CustomViewModel, IDataErrorInfo
{
string IDataErrorInfo.Error
{
get { throw new NotImplementedException(); }
}
string IDataErrorInfo.this[string propertyName] => _validationHandler.Validate(this, propertyName);
}
ValidationHandler.cs
public string Validate(object currentInstance, string propertyName)
{
// BLA BLA BLA BLA BLA
return ReturnErrorString
}
我现在想要的是能够异步完成。我在下面留下的代码不起作用。它没有 return 错误或任何其他错误,只是我的表单打不开,我的应用程序冻结了。
private async Task<string> AsyncValidation(object currentInstance, string propertyName)
{
return await TaskEx.Run(() =>
{
// BLA BLA BLA BLA BLA
return ReturnErrorString
}
);
}
public string Validate(object currentInstance, string propertyName)
{
return AsyncValidation(currentInstance, propertyName).Result;
}
我做错了什么?谢谢
您的新 Validate
函数应如下所示:
public async string Validate(object currentInstance, string propertyName)
{
result = await AsyncValidation(currentInstance, propertyName);
return result;
}
您实际上不能异步实现 IDataErrorInfo
接口,因为它只定义了一个 属性 和一个索引器,其中 none 是或可能是异步实现的。
在索引器中调用 async
方法将不会 使验证异步,因为验证框架不等待索引器本身。您无法真正改变这一点。 async
方法应该一直是 async
,你不应该混合阻塞代码和异步代码:https://msdn.microsoft.com/en-us/magazine/jj991977.aspx.
您可能需要查看 .NET Framework 4.5 中引入的 INotifyDataErrorInfo
接口。此接口确实支持异步验证。有关详细信息和示例,请参阅以下 TechNet 文章:https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx.
当我想异步使用 IDataErrorInfo (.NET 4.0) 时遇到问题。此代码完美运行。
EditViewModel.cs
public class EditViewModel : CustomViewModel, IDataErrorInfo
{
string IDataErrorInfo.Error
{
get { throw new NotImplementedException(); }
}
string IDataErrorInfo.this[string propertyName] => _validationHandler.Validate(this, propertyName);
}
ValidationHandler.cs
public string Validate(object currentInstance, string propertyName)
{
// BLA BLA BLA BLA BLA
return ReturnErrorString
}
我现在想要的是能够异步完成。我在下面留下的代码不起作用。它没有 return 错误或任何其他错误,只是我的表单打不开,我的应用程序冻结了。
private async Task<string> AsyncValidation(object currentInstance, string propertyName)
{
return await TaskEx.Run(() =>
{
// BLA BLA BLA BLA BLA
return ReturnErrorString
}
);
}
public string Validate(object currentInstance, string propertyName)
{
return AsyncValidation(currentInstance, propertyName).Result;
}
我做错了什么?谢谢
您的新 Validate
函数应如下所示:
public async string Validate(object currentInstance, string propertyName)
{
result = await AsyncValidation(currentInstance, propertyName);
return result;
}
您实际上不能异步实现 IDataErrorInfo
接口,因为它只定义了一个 属性 和一个索引器,其中 none 是或可能是异步实现的。
在索引器中调用 async
方法将不会 使验证异步,因为验证框架不等待索引器本身。您无法真正改变这一点。 async
方法应该一直是 async
,你不应该混合阻塞代码和异步代码:https://msdn.microsoft.com/en-us/magazine/jj991977.aspx.
您可能需要查看 .NET Framework 4.5 中引入的 INotifyDataErrorInfo
接口。此接口确实支持异步验证。有关详细信息和示例,请参阅以下 TechNet 文章:https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx.