Perform model validation asynchronously
You can perform model validation asynchronously. To do so, use the following method.
- Call the
CreateAsyncValidationContextmethod of theIModelobject to generate anIAsyncValidationContextobject (asynchronous validation context). - Call the
ValidateAsyncmethod of the generatedIAsyncValidationContextobject to perform model validation asynchronously. - The error information added during validation is included in the
Resultproperty of theIAsyncValidationContextobject. If you want to reflect the error information on the screen, specify the obtained error information as an argument and call theAddErrorsmethod of theIErrorsobject in the UI thread.
using System.Threading.Tasks;
public void ValidateAsync(ICommandContext c, ICommandParams p)
{
IModel model = c.App.Workspace.CurrentModel;
if (model == null)
{
return;
}
//Create an asynchronous validation context
IAsyncValidationContext asyncValidationContext = model.CreateAsyncValidationContext();
Task.Run(async () =>
{
//Execute model validation asynchronously
await asyncValidationContext.ValidateAsync();
if (!asyncValidationContext.Result.IsCanceled && !asyncValidationContext.Result.Failed)
{
//Since the process is executed asynchronously, use the Dispatcher class to execute the process on the UI thread
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
IErrorCollection errors = asyncValidationContext.Result.Errors;
c.App.Workspace.Errors.AddErrors(errors);
});
}
});
}
info
When creating an IAsyncValidationContext object, you can customize the validation content by specifying a ValidationOptions object (validation options). You can also define your own validation using the RegisterOnModelValidate method of the created IAsyncValidationContext object.