Skip to main content

Perform model validation asynchronously

You can perform model validation asynchronously. To do so, use the following method.

  1. Call the CreateAsyncValidationContext method of the IModel object to generate an IAsyncValidationContext object (asynchronous validation context).
  2. Call the ValidateAsync method of the generated IAsyncValidationContext object to perform model validation asynchronously.
  3. The error information added during validation is included in the Result property of the IAsyncValidationContext object. If you want to reflect the error information on the screen, specify the obtained error information as an argument and call the AddErrors method of the IErrors object 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.