public static async Task <List <PredictionResult>?> PredictInput(string client, Ast ast, Token[] astTokens, int millisecondsTimeout) { Requires.Condition(millisecondsTimeout > 0, nameof(millisecondsTimeout)); var predictors = SubsystemManager.GetSubsystems <ICommandPredictor>(); if (predictors.Count == 0) { return(null); } var context = new PredictionContext(ast, astTokens); var tasks = new Task <PredictionResult?> [predictors.Count]; using var cancellationSource = new CancellationTokenSource(); for (int i = 0; i < predictors.Count; i++) { ICommandPredictor predictor = predictors[i]; tasks[i] = Task.Factory.StartNew( state => { var predictor = (ICommandPredictor)state !; SuggestionPackage pkg = predictor.GetSuggestion(client, context, cancellationSource.Token); return(pkg.SuggestionEntries?.Count > 0 ? new PredictionResult(predictor.Id, predictor.Name, pkg.Session, pkg.SuggestionEntries) : null); }, predictor, cancellationSource.Token, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } await Task.WhenAny( Task.WhenAll(tasks), Task.Delay(millisecondsTimeout, cancellationSource.Token)).ConfigureAwait(false); cancellationSource.Cancel(); var resultList = new List <PredictionResult>(predictors.Count); foreach (Task <PredictionResult?> task in tasks) { if (task.IsCompletedSuccessfully) { PredictionResult?result = task.Result; if (result != null) { resultList.Add(result); } } } return(resultList); }
static Func <object?, PredictionResult?> GetCallBack( PredictionClient client, PredictionContext context, CancellationTokenSource cancellationSource) { return(state => { var predictor = (ICommandPredictor)state !; SuggestionPackage pkg = predictor.GetSuggestion(client, context, cancellationSource.Token); return pkg.SuggestionEntries?.Count > 0 ? new PredictionResult(predictor.Id, predictor.Name, pkg.Session, pkg.SuggestionEntries) : null; }); }