public void RetrieveGroups(string searchTerm) { if (repository == null) { throw new InvalidOperationException("You must connect to AD before querying the groups."); } AreGroupsDisplayed = true; AreUsersDisplayed = false; if (tokenSource != null) { tokenSource.Cancel(); } tokenSource = new CancellationTokenSource(); groupTask = groupTask.ContinueWith( t => { IsSearching = true; }, tokenSource.Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext() ).ContinueWith(t => { CancellationToken token = tokenSource.Token; Groups.Clear(); var groups = repository.GetGroups(searchTerm); var models = groups.Select(g => groupMapper.GetModel(g, includeDummy: true)); var modelComparer = KeyComparer <GroupModel> .OrderBy(m => m.Name); foreach (var model in models) { token.ThrowIfCancellationRequested(); int index = Groups.ToSublist().UpperBound(model, modelComparer); Groups.Insert(index, model); } }, tokenSource.Token); groupTask.ContinueWith( t => onErrorOccurred(t.Exception), CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext() ); groupTask.ContinueWith( t => { IsSearching = false; }, tokenSource.Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext() ); }