diff --git a/src/EditorFeatures/CSharp/AutomaticCompletion/Sessions/CurlyBraceCompletionSession.cs b/src/EditorFeatures/CSharp/AutomaticCompletion/Sessions/CurlyBraceCompletionSession.cs index 20aa21d70814b0c64cf6fd75438bb2c4a6abadd5..1664edd86e5d8c90de3d115238998be2cb114ca7 100644 --- a/src/EditorFeatures/CSharp/AutomaticCompletion/Sessions/CurlyBraceCompletionSession.cs +++ b/src/EditorFeatures/CSharp/AutomaticCompletion/Sessions/CurlyBraceCompletionSession.cs @@ -60,19 +60,18 @@ public override void AfterReturn(IBraceCompletionSession session, CancellationTo // alright, it is in right shape. var undoHistory = GetUndoHistory(session.TextView); - using (var transaction = undoHistory.CreateTransaction(EditorFeaturesResources.Brace_Completion)) + using var transaction = undoHistory.CreateTransaction(EditorFeaturesResources.Brace_Completion); + + var document = session.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); + if (document != null) { - var document = session.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); - if (document != null) - { - document.InsertText(session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot) - 1, Environment.NewLine, cancellationToken); - FormatTrackingSpan(session, shouldHonorAutoFormattingOnCloseBraceOption: false, rules: GetFormattingRules(document)); + document.InsertText(session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot) - 1, Environment.NewLine, cancellationToken); + FormatTrackingSpan(session, shouldHonorAutoFormattingOnCloseBraceOption: false, rules: GetFormattingRules(document)); - // put caret at right indentation - PutCaretOnLine(session, session.OpeningPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).GetContainingLineNumber() + 1); + // put caret at right indentation + PutCaretOnLine(session, session.OpeningPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).GetContainingLineNumber() + 1); - transaction.Complete(); - } + transaction.Complete(); } } diff --git a/src/EditorFeatures/Core.Wpf/Options/LegacyEditorConfigDocumentOptionsProvider.cs b/src/EditorFeatures/Core.Wpf/Options/LegacyEditorConfigDocumentOptionsProvider.cs index 40de3632e233cabd6b2323b77e6eb43f5306f8f1..8e350a21093b5acf5ddb6125258a976b5e5ada0e 100644 --- a/src/EditorFeatures/Core.Wpf/Options/LegacyEditorConfigDocumentOptionsProvider.cs +++ b/src/EditorFeatures/Core.Wpf/Options/LegacyEditorConfigDocumentOptionsProvider.cs @@ -179,10 +179,9 @@ public async Task GetOptionsForDocumentAsync(Document document // as in some builds the ICodingConventionsManager captures the thread pool. var conventionsAsync = Task.Run(() => GetConventionContextAsync(path, cancellationToken)); - using (var context = await conventionsAsync.ConfigureAwait(false)) - { - return new DocumentOptions(context.CurrentConventions, _errorLogger); - } + using var context = await conventionsAsync.ConfigureAwait(false); + + return new DocumentOptions(context.CurrentConventions, _errorLogger); } } diff --git a/src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs b/src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs index 2575642018952c70938089d259df5cbe43255a54..89d221445d541a09e72b20737e49642184cfa209 100644 --- a/src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs @@ -111,22 +111,21 @@ public void ExecuteCommand(AutomaticLineEnderCommandArgs args, Action nextHandle return; } - using (var transaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService)) - { - // try to move the caret to the end of the line on which the caret is - args.TextView.TryMoveCaretToAndEnsureVisible(subjectLineWhereCaretIsOn.End); + using var transaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); - // okay, now insert ending if we need to - var newDocument = InsertEndingIfRequired(document, insertionPoint.Value, position.Value, userCancellationToken); + // try to move the caret to the end of the line on which the caret is + args.TextView.TryMoveCaretToAndEnsureVisible(subjectLineWhereCaretIsOn.End); - // format the document and apply the changes to the workspace - FormatAndApply(newDocument, insertionPoint.Value, userCancellationToken); + // okay, now insert ending if we need to + var newDocument = InsertEndingIfRequired(document, insertionPoint.Value, position.Value, userCancellationToken); - // now, insert new line - NextAction(operations, nextHandler); + // format the document and apply the changes to the workspace + FormatAndApply(newDocument, insertionPoint.Value, userCancellationToken); - transaction.Complete(); - } + // now, insert new line + NextAction(operations, nextHandler); + + transaction.Complete(); } } diff --git a/src/EditorFeatures/Core/Implementation/BlockCommentEditing/BaseAbstractBlockCommentEditingCommandHandler.cs b/src/EditorFeatures/Core/Implementation/BlockCommentEditing/BaseAbstractBlockCommentEditingCommandHandler.cs index 25509ec3cba619eeb2f14fd1512922957c2b6c31..28376b162f6946e9c21b315bec47a752ee100a6a 100644 --- a/src/EditorFeatures/Core/Implementation/BlockCommentEditing/BaseAbstractBlockCommentEditingCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/BlockCommentEditing/BaseAbstractBlockCommentEditingCommandHandler.cs @@ -47,16 +47,15 @@ protected bool TryHandleReturnKey(ITextBuffer subjectBuffer, ITextView textView) return false; } - using (var transaction = _undoHistoryRegistry.GetHistory(textView.TextBuffer).CreateTransaction(EditorFeaturesResources.Insert_new_line)) - { - var editorOperations = _editorOperationsFactoryService.GetEditorOperations(textView); + using var transaction = _undoHistoryRegistry.GetHistory(textView.TextBuffer).CreateTransaction(EditorFeaturesResources.Insert_new_line); - editorOperations.InsertNewLine(); - editorOperations.InsertText(exteriorText); + var editorOperations = _editorOperationsFactoryService.GetEditorOperations(textView); - transaction.Complete(); - return true; - } + editorOperations.InsertNewLine(); + editorOperations.InsertText(exteriorText); + + transaction.Complete(); + return true; } protected abstract string GetExteriorTextForNextLine(SnapshotPoint caretPosition); diff --git a/src/EditorFeatures/Core/Implementation/DocumentationComments/AbstractXmlTagCompletionCommandHandler.cs b/src/EditorFeatures/Core/Implementation/DocumentationComments/AbstractXmlTagCompletionCommandHandler.cs index 065444fe2f2b17ee18072452514807469e1b0d2d..6f221b8df4b306ee53e2f75a031ac4399c0a7b58 100644 --- a/src/EditorFeatures/Core/Implementation/DocumentationComments/AbstractXmlTagCompletionCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/DocumentationComments/AbstractXmlTagCompletionCommandHandler.cs @@ -67,18 +67,17 @@ public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, Command protected void InsertTextAndMoveCaret(ITextView textView, ITextBuffer subjectBuffer, SnapshotPoint position, string insertionText, int? finalCaretPosition) { - using (var transaction = _undoHistory.GetHistory(textView.TextBuffer).CreateTransaction("XmlTagCompletion")) - { - subjectBuffer.Insert(position, insertionText); + using var transaction = _undoHistory.GetHistory(textView.TextBuffer).CreateTransaction("XmlTagCompletion"); - if (finalCaretPosition.HasValue) - { - var point = subjectBuffer.CurrentSnapshot.GetPoint(finalCaretPosition.Value); - textView.TryMoveCaretToAndEnsureVisible(point); - } + subjectBuffer.Insert(position, insertionText); - transaction.Complete(); + if (finalCaretPosition.HasValue) + { + var point = subjectBuffer.CurrentSnapshot.GetPoint(finalCaretPosition.Value); + textView.TryMoveCaretToAndEnsureVisible(point); } + + transaction.Complete(); } } } diff --git a/src/EditorFeatures/Core/Implementation/EditAndContinue/ReadOnlyDocumentTracker.cs b/src/EditorFeatures/Core/Implementation/EditAndContinue/ReadOnlyDocumentTracker.cs index b9a96292994048f258eb1e1062272a19718af032..9a48350daaa23de336a9c7bedea315e5f282c692 100644 --- a/src/EditorFeatures/Core/Implementation/EditAndContinue/ReadOnlyDocumentTracker.cs +++ b/src/EditorFeatures/Core/Implementation/EditAndContinue/ReadOnlyDocumentTracker.cs @@ -112,11 +112,10 @@ private void RemoveReadOnlyRegionFromBuffer(DocumentId documentId, IReadOnlyRegi AssertIsForeground(); var textBuffer = GetTextBuffer(_workspace, documentId); - using (var readOnlyEdit = textBuffer.CreateReadOnlyRegionEdit()) - { - readOnlyEdit.RemoveReadOnlyRegion(region); - readOnlyEdit.Apply(); - } + using var readOnlyEdit = textBuffer.CreateReadOnlyRegionEdit(); + + readOnlyEdit.RemoveReadOnlyRegion(region); + readOnlyEdit.Apply(); } private static ITextBuffer GetTextBuffer(Workspace workspace, DocumentId documentId) diff --git a/src/EditorFeatures/Core/Implementation/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs b/src/EditorFeatures/Core/Implementation/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs index ae6f86aa732096c84be802bd3d3dc0a31898c7cf..cdf1b107ef42bf91bfdb2763cc5e32fd8d35473c 100644 --- a/src/EditorFeatures/Core/Implementation/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs @@ -42,10 +42,9 @@ public bool ExecuteCommand(EncapsulateFieldCommandArgs args, CommandExecutionCon return false; } - using (var waitScope = context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Applying_Encapsulate_Field_refactoring)) - { - return Execute(args, waitScope); - } + using var waitScope = context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Applying_Encapsulate_Field_refactoring); + + return Execute(args, waitScope); } private bool Execute(EncapsulateFieldCommandArgs args, IUIThreadOperationScope waitScope) diff --git a/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs b/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs index c3e1f703f8cc1fe4cee1e7bac94ff2598e90c1cd..7f817c417f6b5db7dabdbdd01269ba61d3a04ac0 100644 --- a/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs @@ -238,15 +238,14 @@ private bool TryNotifyFailureToUser(Document document, ExtractMethodResult resul /// private void ApplyChangesToBuffer(ExtractMethodResult extractMethodResult, ITextBuffer subjectBuffer, CancellationToken cancellationToken) { - using (var undoTransaction = _undoManager.GetTextBufferUndoManager(subjectBuffer).TextBufferUndoHistory.CreateTransaction("Extract Method")) - { - // apply extract method code to buffer - var document = extractMethodResult.Document; - document.Project.Solution.Workspace.ApplyDocumentChanges(document, cancellationToken); + using var undoTransaction = _undoManager.GetTextBufferUndoManager(subjectBuffer).TextBufferUndoHistory.CreateTransaction("Extract Method"); - // apply changes - undoTransaction.Complete(); - } + // apply extract method code to buffer + var document = extractMethodResult.Document; + document.Project.Solution.Workspace.ApplyDocumentChanges(document, cancellationToken); + + // apply changes + undoTransaction.Complete(); } } } diff --git a/src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCommitter.cs b/src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCommitter.cs index 9099a14ccf464943d45539c7ee78ff90d20bbe19..da1c5b5bba81f766ce20dcdda8f6dc7c0d2ef068 100644 --- a/src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCommitter.cs +++ b/src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCommitter.cs @@ -262,33 +262,32 @@ private void UpdateWorkspaceForResetOfTypedIdentifier(Workspace workspace, Solut var undoHistory = _undoHistoryRegistry.RegisterHistory(_stateMachine.Buffer); - using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoName)) - using (var localUndoTransaction = undoHistory.CreateTransaction(undoName)) - { - var undoPrimitiveBefore = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false); - localUndoTransaction.AddUndo(undoPrimitiveBefore); + using var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoName); + using var localUndoTransaction = undoHistory.CreateTransaction(undoName); - if (!workspace.TryApplyChanges(newSolution)) - { - Contract.Fail("Rename Tracking could not update solution."); - } + var undoPrimitiveBefore = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false); + localUndoTransaction.AddUndo(undoPrimitiveBefore); - if (!_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: false)) - { - var notificationService = workspace.Services.GetService(); - notificationService.SendNotification( - EditorFeaturesResources.Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated, - EditorFeaturesResources.Rename_Symbol, - NotificationSeverity.Information); - } - - // Never resume tracking session on redo - var undoPrimitiveAfter = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false); - localUndoTransaction.AddUndo(undoPrimitiveAfter); + if (!workspace.TryApplyChanges(newSolution)) + { + Contract.Fail("Rename Tracking could not update solution."); + } - localUndoTransaction.Complete(); - workspaceUndoTransaction.Commit(); + if (!_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: false)) + { + var notificationService = workspace.Services.GetService(); + notificationService.SendNotification( + EditorFeaturesResources.Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated, + EditorFeaturesResources.Rename_Symbol, + NotificationSeverity.Information); } + + // Never resume tracking session on redo + var undoPrimitiveAfter = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false); + localUndoTransaction.AddUndo(undoPrimitiveAfter); + + localUndoTransaction.Complete(); + workspaceUndoTransaction.Commit(); } } } diff --git a/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentState.cs b/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentState.cs index d19a714eb9b11fd6bda68c326a94251229bb6014..3703ce5a904fe910bbffebb9f909385844e28dd7 100644 --- a/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentState.cs +++ b/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentState.cs @@ -48,29 +48,28 @@ protected override Data TryGetExistingData(Stream stream, Document value, Cancel protected override void WriteTo(Stream stream, Data data, CancellationToken cancellationToken) { - using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken)) - { - writer.WriteString(FormatVersion); - data.TextVersion.WriteTo(writer); - data.SyntaxVersion.WriteTo(writer); + using var writer = new ObjectWriter(stream, cancellationToken: cancellationToken); - writer.WriteInt32(data.Items.Length); + writer.WriteString(FormatVersion); + data.TextVersion.WriteTo(writer); + data.SyntaxVersion.WriteTo(writer); - foreach (var item in data.Items.OfType()) - { - cancellationToken.ThrowIfCancellationRequested(); + writer.WriteInt32(data.Items.Length); + + foreach (var item in data.Items.OfType()) + { + cancellationToken.ThrowIfCancellationRequested(); - writer.WriteInt32(item.Priority); - writer.WriteString(item.Message); + writer.WriteInt32(item.Priority); + writer.WriteString(item.Message); - writer.WriteString(item.OriginalFilePath); - writer.WriteInt32(item.OriginalLine); - writer.WriteInt32(item.OriginalColumn); + writer.WriteString(item.OriginalFilePath); + writer.WriteInt32(item.OriginalLine); + writer.WriteInt32(item.OriginalColumn); - writer.WriteString(item.MappedFilePath); - writer.WriteInt32(item.MappedLine); - writer.WriteInt32(item.MappedColumn); - } + writer.WriteString(item.MappedFilePath); + writer.WriteInt32(item.MappedLine); + writer.WriteInt32(item.MappedColumn); } } diff --git a/src/VisualStudio/CSharp/Impl/CodeModel/MethodXml/MethodXmlBuilder.cs b/src/VisualStudio/CSharp/Impl/CodeModel/MethodXml/MethodXmlBuilder.cs index 49dcf79f09888debd59ce3c077109b731f8b39df..a46193d12d714619bfdf22fd07d78154b493ed65 100644 --- a/src/VisualStudio/CSharp/Impl/CodeModel/MethodXml/MethodXmlBuilder.cs +++ b/src/VisualStudio/CSharp/Impl/CodeModel/MethodXml/MethodXmlBuilder.cs @@ -42,12 +42,11 @@ private void GenerateComments(SyntaxTriviaList triviaList) var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition() ?? -1; if (firstNonWhitespacePosition == trivia.SpanStart) { - using (var tag = CommentTag()) - { - // Skip initial slashes - var trimmedComment = trivia.ToString().Substring(2); - EncodedText(trimmedComment); - } + using var tag = CommentTag(); + + // Skip initial slashes + var trimmedComment = trivia.ToString().Substring(2); + EncodedText(trimmedComment); } } } diff --git a/src/VisualStudio/CSharp/Test/Debugging/LocationInfoGetterTests.cs b/src/VisualStudio/CSharp/Test/Debugging/LocationInfoGetterTests.cs index ff6db39c12edccbe78d002c31aba8d76bb3ac378..ceb6b70a8cf3a510552b186f280509e23a3e3d21 100644 --- a/src/VisualStudio/CSharp/Test/Debugging/LocationInfoGetterTests.cs +++ b/src/VisualStudio/CSharp/Test/Debugging/LocationInfoGetterTests.cs @@ -17,18 +17,17 @@ public class LocationInfoGetterTests { private async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null) { - using (var workspace = TestWorkspace.CreateCSharp(markup, parseOptions)) - { - var testDocument = workspace.Documents.Single(); - var position = testDocument.CursorPosition.Value; - var locationInfo = await LocationInfoGetter.GetInfoAsync( - workspace.CurrentSolution.Projects.Single().Documents.Single(), - position, - CancellationToken.None); - - Assert.Equal(expectedName, locationInfo.Name); - Assert.Equal(expectedLineOffset, locationInfo.LineOffset); - } + using var workspace = TestWorkspace.CreateCSharp(markup, parseOptions); + + var testDocument = workspace.Documents.Single(); + var position = testDocument.CursorPosition.Value; + var locationInfo = await LocationInfoGetter.GetInfoAsync( + workspace.CurrentSolution.Projects.Single().Documents.Single(), + position, + CancellationToken.None); + + Assert.Equal(expectedName, locationInfo.Name); + Assert.Equal(expectedLineOffset, locationInfo.LineOffset); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] diff --git a/src/VisualStudio/CSharp/Test/Debugging/NameResolverTests.cs b/src/VisualStudio/CSharp/Test/Debugging/NameResolverTests.cs index d068faeb7f92c1bfdc61f383c43eff4d7acf8f4b..08df06d909b35b4c32216c7eada9ce48ed8395e5 100644 --- a/src/VisualStudio/CSharp/Test/Debugging/NameResolverTests.cs +++ b/src/VisualStudio/CSharp/Test/Debugging/NameResolverTests.cs @@ -27,12 +27,11 @@ private async Task TestAsync(string text, string searchText, params string[] exp [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestCSharpLanguageDebugInfoCreateNameResolver() { - using (var workspace = TestWorkspace.CreateCSharp(" ")) - { - var debugInfo = new CSharpBreakpointResolutionService(); - var results = await debugInfo.ResolveBreakpointsAsync(workspace.CurrentSolution, "goo", CancellationToken.None); - Assert.Equal(0, results.Count()); - } + using var workspace = TestWorkspace.CreateCSharp(" "); + + var debugInfo = new CSharpBreakpointResolutionService(); + var results = await debugInfo.ResolveBreakpointsAsync(workspace.CurrentSolution, "goo", CancellationToken.None); + Assert.Equal(0, results.Count()); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] diff --git a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs b/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs index 6696ec56dd2dbd30c7071c144f25071345006b56..accf136e491f79bda2e2769ba2e22548addb98b1 100644 --- a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs +++ b/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs @@ -337,20 +337,19 @@ void M() MyEvent +$$ } }"; - using (var testState = EventHookupTestState.CreateTestState(markup)) - { - testState.SendTypeChar('='); - await testState.WaitForAsynchronousOperationsAsync(); - testState.AssertShowing("C_MyEvent;"); + using var testState = EventHookupTestState.CreateTestState(markup); - testState.SendTypeChar(' '); - await testState.WaitForAsynchronousOperationsAsync(); - testState.AssertShowing("C_MyEvent;"); + testState.SendTypeChar('='); + await testState.WaitForAsynchronousOperationsAsync(); + testState.AssertShowing("C_MyEvent;"); - testState.SendBackspace(); - await testState.WaitForAsynchronousOperationsAsync(); - testState.AssertNotShowing(); - } + testState.SendTypeChar(' '); + await testState.WaitForAsynchronousOperationsAsync(); + testState.AssertShowing("C_MyEvent;"); + + testState.SendBackspace(); + await testState.WaitForAsynchronousOperationsAsync(); + testState.AssertNotShowing(); } [WpfFact, Trait(Traits.Feature, Traits.Features.EventHookup)] diff --git a/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs b/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs index 817f10b6b1aeee7e425c92e5b0ff349bb5c90929..7bf8da22686814bb7d6650ec513a0a9e432b8c2e 100644 --- a/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs +++ b/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs @@ -248,60 +248,59 @@ private IEnumerable FilterTextChanges(SourceText originalText, List< yield break; } - using (var pooledObject = SharedPools.Default>().GetPooledObject()) + using var pooledObject = SharedPools.Default>().GetPooledObject(); + + var changeQueue = pooledObject.Object; + changeQueue.AddRange(changes); + + var spanIndex = 0; + var changeIndex = 0; + for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++) { - var changeQueue = pooledObject.Object; - changeQueue.AddRange(changes); + var visibleSpan = editorVisibleSpansInOriginal[spanIndex]; + var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true); - var spanIndex = 0; - var changeIndex = 0; - for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++) + for (; changeIndex < changeQueue.Count; changeIndex++) { - var visibleSpan = editorVisibleSpansInOriginal[spanIndex]; - var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true); + var change = changeQueue[changeIndex]; - for (; changeIndex < changeQueue.Count; changeIndex++) + // easy case first + if (change.Span.End < visibleSpan.Start) { - var change = changeQueue[changeIndex]; + // move to next change + continue; + } - // easy case first - if (change.Span.End < visibleSpan.Start) - { - // move to next change - continue; - } + if (visibleSpan.End < change.Span.Start) + { + // move to next visible span + break; + } - if (visibleSpan.End < change.Span.Start) - { - // move to next visible span - break; - } + // make sure we are not replacing whitespace around start and at the end of visible span + if (WhitespaceOnEdges(originalText, visibleTextSpan, change)) + { + continue; + } - // make sure we are not replacing whitespace around start and at the end of visible span - if (WhitespaceOnEdges(originalText, visibleTextSpan, change)) - { - continue; - } + if (visibleSpan.Contains(change.Span)) + { + yield return change; + continue; + } - if (visibleSpan.Contains(change.Span)) + // now it is complex case where things are intersecting each other + var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList(); + if (subChanges.Count > 0) + { + if (subChanges.Count == 1 && subChanges[0] == change) { - yield return change; + // we can't break it. not much we can do here. just don't touch and ignore this change continue; } - // now it is complex case where things are intersecting each other - var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList(); - if (subChanges.Count > 0) - { - if (subChanges.Count == 1 && subChanges[0] == change) - { - // we can't break it. not much we can do here. just don't touch and ignore this change - continue; - } - - changeQueue.InsertRange(changeIndex + 1, subChanges); - continue; - } + changeQueue.InsertRange(changeIndex + 1, subChanges); + continue; } } } diff --git a/src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.cs b/src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.cs index 146f0d221c1d1fe4a2111224a5a2d2ecd8a7fb6c..e2ae3707a73fe903cef3cc897eb4453192b84268 100644 --- a/src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.cs +++ b/src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.cs @@ -465,10 +465,9 @@ protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assem if (type.TypeKind == TypeKind.Array) { var arrayType = (IArrayTypeSymbol)type; - using (var tag = ArrayTypeTag(arrayType.Rank)) - { - GenerateType(arrayType.ElementType, @implicit, assemblyQualify); - } + using var tag = ArrayTypeTag(arrayType.Rank); + + GenerateType(arrayType.ElementType, @implicit, assemblyQualify); } else { diff --git a/src/Workspaces/Core/Portable/FindSymbols/Declarations/DeclarationFinder_SourceDeclarations.cs b/src/Workspaces/Core/Portable/FindSymbols/Declarations/DeclarationFinder_SourceDeclarations.cs index 1aca1feb562ba845754ac47e885b82122b9114f7..6a29e6121a8f4911a9729dd2a9b6708938dfb2d3 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/Declarations/DeclarationFinder_SourceDeclarations.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/Declarations/DeclarationFinder_SourceDeclarations.cs @@ -248,12 +248,11 @@ internal static partial class DeclarationFinder { var list = ArrayBuilder.GetInstance(); - using (var query = SearchQuery.Create(name, ignoreCase)) - { - await AddCompilationDeclarationsWithNormalQueryAsync( - project, query, filter, list, cancellationToken).ConfigureAwait(false); - return list.ToImmutableAndFree(); - } + using var query = SearchQuery.Create(name, ignoreCase); + + await AddCompilationDeclarationsWithNormalQueryAsync( + project, query, filter, list, cancellationToken).ConfigureAwait(false); + return list.ToImmutableAndFree(); } private static async Task> FindSourceDeclarationsWithPatternInCurrentProcessAsync( @@ -273,27 +272,25 @@ internal static partial class DeclarationFinder // If we don't have a dot in the pattern, just make a pattern matcher for the entire // pattern they passed in. Otherwise, make a pattern matcher just for the part after // the dot. - using (var nameMatcher = PatternMatcher.CreatePatternMatcher(namePart, includeMatchedSpans: false)) - using (var query = SearchQuery.CreateCustom(nameMatcher.Matches)) + using var nameMatcher = PatternMatcher.CreatePatternMatcher(namePart, includeMatchedSpans: false); + using var query = SearchQuery.CreateCustom(nameMatcher.Matches); + + var symbolAndProjectIds = await searchAsync(query).ConfigureAwait(false); + + if (symbolAndProjectIds.Length == 0 || + !isDottedPattern) { - var symbolAndProjectIds = await searchAsync(query).ConfigureAwait(false); - - if (symbolAndProjectIds.Length == 0 || - !isDottedPattern) - { - // If it wasn't a dotted pattern, or we didn't get anything back, then we're done. - // We can just return whatever set of results we got so far. - return symbolAndProjectIds; - } - - // Ok, we had a dotted pattern. Have to see if the symbol's container matches the - // pattern as well. - using (var containerPatternMatcher = PatternMatcher.CreateDotSeparatedContainerMatcher(containerPart)) - { - return symbolAndProjectIds.WhereAsArray(t => - containerPatternMatcher.Matches(GetContainer(t.Symbol))); - } + // If it wasn't a dotted pattern, or we didn't get anything back, then we're done. + // We can just return whatever set of results we got so far. + return symbolAndProjectIds; } + + // Ok, we had a dotted pattern. Have to see if the symbol's container matches the + // pattern as well. + using var containerPatternMatcher = PatternMatcher.CreateDotSeparatedContainerMatcher(containerPart); + + return symbolAndProjectIds.WhereAsArray(t => + containerPatternMatcher.Matches(GetContainer(t.Symbol))); } internal static Task> FindSourceDeclarationsWithPatternInCurrentProcessAsync( diff --git a/src/Workspaces/Remote/ServiceHub/Services/CodeAnalysisService_SymbolFinder.cs b/src/Workspaces/Remote/ServiceHub/Services/CodeAnalysisService_SymbolFinder.cs index dc7e4eb518c2482d79a66fecf8fe45c55829d98b..a916a71341df42f49579217919575ac29f7369fb 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/CodeAnalysisService_SymbolFinder.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/CodeAnalysisService_SymbolFinder.cs @@ -78,13 +78,12 @@ public Task FindLiteralReferencesAsync(object value, TypeCode typeCode, Cancella var solution = await GetSolutionAsync(cancellationToken).ConfigureAwait(false); var project = solution.GetProject(projectId); - using (var query = SearchQuery.Create(name, searchKind)) - { - var result = await DeclarationFinder.FindAllDeclarationsWithNormalQueryInCurrentProcessAsync( - project, query, criteria, cancellationToken).ConfigureAwait(false); + using var query = SearchQuery.Create(name, searchKind); - return (IList)result.SelectAsArray(SerializableSymbolAndProjectId.Dehydrate); - } + var result = await DeclarationFinder.FindAllDeclarationsWithNormalQueryInCurrentProcessAsync( + project, query, criteria, cancellationToken).ConfigureAwait(false); + + return (IList)result.SelectAsArray(SerializableSymbolAndProjectId.Dehydrate); } }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/SnapshotService.JsonRpcAssetSource.cs b/src/Workspaces/Remote/ServiceHub/Services/SnapshotService.JsonRpcAssetSource.cs index 662f76b16afd8e0f8b4c8d83ad47b1c49e0a9f01..e7d4790060314b2a1a1519565e340d972e55c451 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/SnapshotService.JsonRpcAssetSource.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/SnapshotService.JsonRpcAssetSource.cs @@ -83,33 +83,32 @@ private bool ReportUnlessCanceled(Exception ex, CancellationToken cancellationTo { var results = new List<(Checksum, object)>(); - using (var reader = ObjectReader.TryGetReader(stream, cancellationToken)) - { - Debug.Assert(reader != null, + using var reader = ObjectReader.TryGetReader(stream, cancellationToken); + + Debug.Assert(reader != null, @"We only ge a reader for data transmitted between live processes. This data should always be correct as we're never persisting the data between sessions."); - var responseScopeId = reader.ReadInt32(); - Contract.ThrowIfFalse(scopeId == responseScopeId); + var responseScopeId = reader.ReadInt32(); + Contract.ThrowIfFalse(scopeId == responseScopeId); - var count = reader.ReadInt32(); - Contract.ThrowIfFalse(count == checksums.Count); - - for (var i = 0; i < count; i++) - { - var responseChecksum = Checksum.ReadFrom(reader); - Contract.ThrowIfFalse(checksums.Contains(responseChecksum)); + var count = reader.ReadInt32(); + Contract.ThrowIfFalse(count == checksums.Count); - var kind = (WellKnownSynchronizationKind)reader.ReadInt32(); + for (var i = 0; i < count; i++) + { + var responseChecksum = Checksum.ReadFrom(reader); + Contract.ThrowIfFalse(checksums.Contains(responseChecksum)); - // in service hub, cancellation means simply closed stream - var @object = serializerService.Deserialize(kind, reader, cancellationToken); + var kind = (WellKnownSynchronizationKind)reader.ReadInt32(); - results.Add((responseChecksum, @object)); - } + // in service hub, cancellation means simply closed stream + var @object = serializerService.Deserialize(kind, reader, cancellationToken); - return results; + results.Add((responseChecksum, @object)); } + + return results; } private static string GetRequestLogInfo(int serviceId, IEnumerable checksums)