当我想异步使用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
}我现在想要的是能够异步地完成这个任务。下面我留下的代码不起作用。它不返回错误或任何东西,只有我的表单不打开,我的应用程序冻结。
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;
}我做错了什么?谢谢
发布于 2017-04-02 19:06:17
实际上不能异步实现IDataErrorInfo接口,因为它只定义了属性和索引器,而这些属性和索引器都不是异步实现的,也可能是异步实现的。
在索引器中调用async方法不会使验证异步,因为验证框架没有等待索引器本身。要真正改变这种状况,你无能为力。async方法应该一直是async,不应该将阻塞和异步代码混合在一起:https://msdn.microsoft.com/en-us/magazine/jj991977.aspx。
您可能需要查看在INotifyDataErrorInfo Framework4.5中引入的.NET接口。此接口确实支持异步验证。有关更多信息和示例,请参阅以下TechNet文章:https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx。
发布于 2017-04-01 05:07:20
您的新Validate函数应该如下所示:
public async string Validate(object currentInstance, string propertyName)
{
result = await AsyncValidation(currentInstance, propertyName);
return result;
}https://stackoverflow.com/questions/43151643
复制相似问题