Perform model validation asynchronously
You can perform model validation asynchronously. To do so, use the following method.
- Call the
CreateAsyncValidationContext
method of theIModel
object to generate anIAsyncValidationContext
object (asynchronous validation context). - Call the
ValidateAsync
method of the generatedIAsyncValidationContext
object to perform model validation asynchronously. - The error information added during validation is included in the
Result
property of theIAsyncValidationContext
object. If you want to reflect the error information on the screen, specify the obtained error information as an argument and call theAddErrors
method of theIErrors
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.