提交 6c607c05 编写于 作者: C Cyrus Najmabadi

Use simple usings

上级 7177e45f
......@@ -122,26 +122,25 @@ protected void ApplyReplacementText(ITextBuffer subjectBuffer, ITextUndoHistory
// roll back to the initial state for the buffer after conflict resolution
this.UndoTemporaryEdits(subjectBuffer, disconnect: false, undoConflictResolution: replacementText == string.Empty);
using (var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(replacementText)))
using (var edit = subjectBuffer.CreateEdit(EditOptions.None, null, propagateSpansEditTag))
using var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(replacementText));
using var edit = subjectBuffer.CreateEdit(EditOptions.None, null, propagateSpansEditTag);
foreach (var span in spans)
{
foreach (var span in spans)
if (span.GetText(subjectBuffer.CurrentSnapshot) != replacementText)
{
if (span.GetText(subjectBuffer.CurrentSnapshot) != replacementText)
{
edit.Replace(span.GetSpan(subjectBuffer.CurrentSnapshot), replacementText);
}
edit.Replace(span.GetSpan(subjectBuffer.CurrentSnapshot), replacementText);
}
}
edit.ApplyAndLogExceptions();
if (!edit.HasEffectiveChanges && !this.UndoStack.Any())
{
transaction.Cancel();
}
else
{
transaction.Complete();
}
edit.ApplyAndLogExceptions();
if (!edit.HasEffectiveChanges && !this.UndoStack.Any())
{
transaction.Cancel();
}
else
{
transaction.Complete();
}
}
......
......@@ -97,44 +97,43 @@ private void UpdateReadOnlyRegions(bool removeOnly = false)
return;
}
using (var readOnlyEdit = _subjectBuffer.CreateReadOnlyRegionEdit())
{
foreach (var oldReadOnlyRegion in _readOnlyRegions)
{
readOnlyEdit.RemoveReadOnlyRegion(oldReadOnlyRegion);
}
using var readOnlyEdit = _subjectBuffer.CreateReadOnlyRegionEdit();
_readOnlyRegions.Clear();
foreach (var oldReadOnlyRegion in _readOnlyRegions)
{
readOnlyEdit.RemoveReadOnlyRegion(oldReadOnlyRegion);
}
if (!removeOnly)
{
// We will compute the new read only regions to be all spans that are not currently in an editable span
var editableSpans = GetEditableSpansForSnapshot(_subjectBuffer.CurrentSnapshot);
var entireBufferSpan = _subjectBuffer.CurrentSnapshot.GetSnapshotSpanCollection();
var newReadOnlySpans = NormalizedSnapshotSpanCollection.Difference(entireBufferSpan, new NormalizedSnapshotSpanCollection(editableSpans));
_readOnlyRegions.Clear();
foreach (var newReadOnlySpan in newReadOnlySpans)
{
_readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(newReadOnlySpan, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow, _isBufferReadOnly));
}
if (!removeOnly)
{
// We will compute the new read only regions to be all spans that are not currently in an editable span
var editableSpans = GetEditableSpansForSnapshot(_subjectBuffer.CurrentSnapshot);
var entireBufferSpan = _subjectBuffer.CurrentSnapshot.GetSnapshotSpanCollection();
var newReadOnlySpans = NormalizedSnapshotSpanCollection.Difference(entireBufferSpan, new NormalizedSnapshotSpanCollection(editableSpans));
// The spans we added allow typing at the start and end. We'll add extra
// zero-width read-only regions at the start and end of the file to fix this,
// but only if we don't have an identifier at the start or end that _would_ let
// them type there.
if (editableSpans.All(s => s.Start > 0))
{
_readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly));
}
foreach (var newReadOnlySpan in newReadOnlySpans)
{
_readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(newReadOnlySpan, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow, _isBufferReadOnly));
}
if (editableSpans.All(s => s.End < _subjectBuffer.CurrentSnapshot.Length))
{
_readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(_subjectBuffer.CurrentSnapshot.Length, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly));
}
// The spans we added allow typing at the start and end. We'll add extra
// zero-width read-only regions at the start and end of the file to fix this,
// but only if we don't have an identifier at the start or end that _would_ let
// them type there.
if (editableSpans.All(s => s.Start > 0))
{
_readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly));
}
readOnlyEdit.Apply();
if (editableSpans.All(s => s.End < _subjectBuffer.CurrentSnapshot.Length))
{
_readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(_subjectBuffer.CurrentSnapshot.Length, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly));
}
}
readOnlyEdit.Apply();
}
private void OnTextViewClosed(object sender, EventArgs e)
......
......@@ -77,12 +77,11 @@ public void CreateConflictResolutionUndoTransaction(ITextBuffer subjectBuffer, A
undoHistory.Undo(1);
}
using (var undoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.Start_Rename))
{
applyEdit();
undoTransaction.Complete();
UndoManagers[subjectBuffer].ConflictResolutionUndoTransaction = undoTransaction;
}
using var undoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.Start_Rename);
applyEdit();
undoTransaction.Complete();
UndoManagers[subjectBuffer].ConflictResolutionUndoTransaction = undoTransaction;
}
public void UndoTemporaryEdits(ITextBuffer subjectBuffer, bool disconnect)
......
......@@ -529,27 +529,26 @@ private async Task<XElement> DownloadFileAsync(string serverPath)
// minutes ago, then the client will attempt to download the file.
// In the interim period null will be returned from client.ReadFile.
var pollingMinutes = (int)TimeSpan.FromDays(1).TotalMinutes;
using (var client = _service._remoteControlService.CreateClient(HostId, serverPath, pollingMinutes))
using var client = _service._remoteControlService.CreateClient(HostId, serverPath, pollingMinutes);
await _service.LogInfoAsync("Creating download client completed").ConfigureAwait(false);
// Poll the client every minute until we get the file.
while (true)
{
await _service.LogInfoAsync("Creating download client completed").ConfigureAwait(false);
_service._updateCancellationToken.ThrowIfCancellationRequested();
// Poll the client every minute until we get the file.
while (true)
var resultOpt = await TryDownloadFileAsync(client).ConfigureAwait(false);
if (resultOpt == null)
{
_service._updateCancellationToken.ThrowIfCancellationRequested();
var resultOpt = await TryDownloadFileAsync(client).ConfigureAwait(false);
if (resultOpt == null)
{
var delay = _service._delayService.CachePollDelay;
await _service.LogInfoAsync($"File not downloaded. Trying again in {delay}").ConfigureAwait(false);
await Task.Delay(delay, _service._updateCancellationToken).ConfigureAwait(false);
}
else
{
// File was downloaded.
return resultOpt;
}
var delay = _service._delayService.CachePollDelay;
await _service.LogInfoAsync($"File not downloaded. Trying again in {delay}").ConfigureAwait(false);
await Task.Delay(delay, _service._updateCancellationToken).ConfigureAwait(false);
}
else
{
// File was downloaded.
return resultOpt;
}
}
}
......
......@@ -97,27 +97,26 @@ private bool TryExecuteCommand(int caretPosition, Document document, CommandExec
{
try
{
using (var token = _asyncListener.BeginAsyncOperation(nameof(StreamingFindReferencesAsync)))
using var token = _asyncListener.BeginAsyncOperation(nameof(StreamingFindReferencesAsync));
// Let the presented know we're starting a search. It will give us back
// the context object that the FAR service will push results into.
var context = presenter.StartSearch(
EditorFeaturesResources.Find_References, supportsReferences: true);
using (Logger.LogBlock(
FunctionId.CommandHandler_FindAllReference,
KeyValueLogMessage.Create(LogType.UserAction, m => m["type"] = "streaming"),
context.CancellationToken))
{
// Let the presented know we're starting a search. It will give us back
// the context object that the FAR service will push results into.
var context = presenter.StartSearch(
EditorFeaturesResources.Find_References, supportsReferences: true);
using (Logger.LogBlock(
FunctionId.CommandHandler_FindAllReference,
KeyValueLogMessage.Create(LogType.UserAction, m => m["type"] = "streaming"),
context.CancellationToken))
{
await findUsagesService.FindReferencesAsync(document, caretPosition, context).ConfigureAwait(false);
// Note: we don't need to put this in a finally. The only time we might not hit
// this is if cancellation or another error gets thrown. In the former case,
// that means that a new search has started. We don't care about telling the
// context it has completed. In the latter case something wrong has happened
// and we don't want to run any more code in this particular context.
await context.OnCompletedAsync().ConfigureAwait(false);
}
await findUsagesService.FindReferencesAsync(document, caretPosition, context).ConfigureAwait(false);
// Note: we don't need to put this in a finally. The only time we might not hit
// this is if cancellation or another error gets thrown. In the former case,
// that means that a new search has started. We don't care about telling the
// context it has completed. In the latter case something wrong has happened
// and we don't want to run any more code in this particular context.
await context.OnCompletedAsync().ConfigureAwait(false);
}
}
catch (OperationCanceledException)
......
......@@ -120,11 +120,10 @@ internal bool ExecuteCommand(ITextView textView, ITextBuffer subjectBuffer, Oper
if (operation == Operation.Uncomment)
{
using (var transaction = new CaretPreservingEditTransaction(title, textView, _undoHistoryRegistry, _editorOperationsFactoryService))
{
Format(service, subjectBuffer.CurrentSnapshot, trackingSpans, CancellationToken.None);
transaction.Complete();
}
using var transaction = new CaretPreservingEditTransaction(title, textView, _undoHistoryRegistry, _editorOperationsFactoryService);
Format(service, subjectBuffer.CurrentSnapshot, trackingSpans, CancellationToken.None);
transaction.Complete();
}
if (trackingSpans.Any())
......
......@@ -69,13 +69,12 @@ private void TrackDocument(DocumentId documentId)
}
var textBuffer = GetTextBuffer(_workspace, documentId);
using (var readOnlyEdit = textBuffer.CreateReadOnlyRegionEdit())
{
_readOnlyRegions.Add(documentId, readOnlyEdit.CreateDynamicReadOnlyRegion(Span.FromBounds(0, readOnlyEdit.Snapshot.Length), SpanTrackingMode.EdgeInclusive, EdgeInsertionMode.Deny,
isEdit => IsRegionReadOnly(documentId, isEdit)));
using var readOnlyEdit = textBuffer.CreateReadOnlyRegionEdit();
readOnlyEdit.Apply();
}
_readOnlyRegions.Add(documentId, readOnlyEdit.CreateDynamicReadOnlyRegion(Span.FromBounds(0, readOnlyEdit.Snapshot.Length), SpanTrackingMode.EdgeInclusive, EdgeInsertionMode.Deny,
isEdit => IsRegionReadOnly(documentId, isEdit)));
readOnlyEdit.Apply();
}
private bool IsRegionReadOnly(DocumentId documentId, bool isEdit)
......
......@@ -227,22 +227,21 @@ private void UpdateWorkspaceForResetOfTypedIdentifier(Workspace workspace, Solut
// deal with the state machine.
var undoHistory = _undoHistoryRegistry.RegisterHistory(_stateMachine.Buffer);
using (var localUndoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.Text_Buffer_Change))
{
var undoPrimitiveBefore = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: true);
localUndoTransaction.AddUndo(undoPrimitiveBefore);
if (!workspace.TryApplyChanges(newSolution))
{
Contract.Fail("Rename Tracking could not update solution.");
}
using var localUndoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.Text_Buffer_Change);
// Never resume tracking session on redo
var undoPrimitiveAfter = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false);
localUndoTransaction.AddUndo(undoPrimitiveAfter);
var undoPrimitiveBefore = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: true);
localUndoTransaction.AddUndo(undoPrimitiveBefore);
localUndoTransaction.Complete();
if (!workspace.TryApplyChanges(newSolution))
{
Contract.Fail("Rename Tracking could not update solution.");
}
// Never resume tracking session on redo
var undoPrimitiveAfter = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false);
localUndoTransaction.AddUndo(undoPrimitiveAfter);
localUndoTransaction.Complete();
}
private void UpdateWorkspaceForGlobalIdentifierRename(
......
......@@ -84,11 +84,10 @@ private SourceText CreateTextInternal(Stream stream, Encoding encoding, Cancella
cancellationToken.ThrowIfCancellationRequested();
stream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
{
var buffer = CreateTextBuffer(reader, cancellationToken);
return buffer.CurrentSnapshot.AsRoslynText(_textBufferCloneService, reader.CurrentEncoding ?? Encoding.UTF8);
}
using var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true);
var buffer = CreateTextBuffer(reader, cancellationToken);
return buffer.CurrentSnapshot.AsRoslynText(_textBufferCloneService, reader.CurrentEncoding ?? Encoding.UTF8);
}
}
}
......
......@@ -53,11 +53,10 @@ public VSCommanding.CommandState GetCommandState(NavigateToPreviousHighlightedRe
private VSCommanding.CommandState GetCommandStateImpl(EditorCommandArgs args)
{
using (var tagAggregator = _tagAggregatorFactory.CreateTagAggregator<NavigableHighlightTag>(args.TextView))
{
var tagUnderCursor = FindTagUnderCaret(tagAggregator, args.TextView);
return tagUnderCursor == null ? VSCommanding.CommandState.Unavailable : VSCommanding.CommandState.Available;
}
using var tagAggregator = _tagAggregatorFactory.CreateTagAggregator<NavigableHighlightTag>(args.TextView);
var tagUnderCursor = FindTagUnderCaret(tagAggregator, args.TextView);
return tagUnderCursor == null ? VSCommanding.CommandState.Unavailable : VSCommanding.CommandState.Available;
}
public bool ExecuteCommand(NavigateToNextHighlightedReferenceCommandArgs args, CommandExecutionContext context)
......
......@@ -104,18 +104,17 @@ where intersection.All(intersectionSpan => mappedSpan.IntersectsWith(intersectio
public void ApplyReplacementText(string replacementText)
{
using (var edit = _subjectBuffer.CreateEdit(new EditOptions(), null, s_propagateSpansEditTag))
using var edit = _subjectBuffer.CreateEdit(new EditOptions(), null, s_propagateSpansEditTag);
foreach (var span in _trackingSpans)
{
foreach (var span in _trackingSpans)
if (span.GetText(_subjectBuffer.CurrentSnapshot) != replacementText)
{
if (span.GetText(_subjectBuffer.CurrentSnapshot) != replacementText)
{
edit.Replace(span.GetSpan(_subjectBuffer.CurrentSnapshot), replacementText);
}
edit.Replace(span.GetSpan(_subjectBuffer.CurrentSnapshot), replacementText);
}
edit.ApplyAndLogExceptions();
}
edit.ApplyAndLogExceptions();
}
}
}
......@@ -382,25 +382,24 @@ private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextC
SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText)
{
// these are expensive. but hopefully we don't hit this as much except the boundary cases.
using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject())
using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject())
{
var leftReplacementMap = leftPool.Object;
var rightReplacementMap = rightPool.Object;
GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out var leftTextWithReplacement, out var rightTextWithReplacement);
using var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject();
using var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject();
var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement);
var leftReplacementMap = leftPool.Object;
var rightReplacementMap = rightPool.Object;
GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out var leftTextWithReplacement, out var rightTextWithReplacement);
foreach (var difference in diffResult)
{
var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap);
var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap);
var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement);
var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);
if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out var textChange))
{
yield return textChange;
}
foreach (var difference in diffResult)
{
var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap);
var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap);
var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);
if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out var textChange))
{
yield return textChange;
}
}
}
......
......@@ -41,42 +41,41 @@ internal static partial class Extensions
{
Task task = null;
using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
using (var stream = new ServerDirectStream())
{
try
{
// send request by adding direct stream name to end of arguments
task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken);
// if invoke throws an exception, make sure we raise cancellation.
RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken);
using var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
using var stream = new ServerDirectStream();
// wait for asset source to respond
await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false);
try
{
// send request by adding direct stream name to end of arguments
task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken);
// run user task with direct stream
await funcWithDirectStreamAsync(stream, mergedCancellation.Token).ConfigureAwait(false);
// if invoke throws an exception, make sure we raise cancellation.
RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken);
// wait task to finish
await task.ConfigureAwait(false);
}
catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken))
{
// important to use cancelationToken here rather than mergedCancellationToken.
// there is a slight delay when merged cancellation token will be notified once cancellation token
// is raised, it can cause one to be in cancelled mode and the other is not. here, one we
// actually care is the cancellation token given in, not the merged cancellation token.
// but we need merged one to cancel operation if InvokeAsync has failed. if it failed without
// cancellation token is raised, then we do want to have watson report
cancellationToken.ThrowIfCancellationRequested();
// wait for asset source to respond
await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false);
// record reason why task got aborted. use NFW here since we don't want to
// crash VS on explicitly killing OOP.
task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed");
// run user task with direct stream
await funcWithDirectStreamAsync(stream, mergedCancellation.Token).ConfigureAwait(false);
throw;
}
// wait task to finish
await task.ConfigureAwait(false);
}
catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken))
{
// important to use cancelationToken here rather than mergedCancellationToken.
// there is a slight delay when merged cancellation token will be notified once cancellation token
// is raised, it can cause one to be in cancelled mode and the other is not. here, one we
// actually care is the cancellation token given in, not the merged cancellation token.
// but we need merged one to cancel operation if InvokeAsync has failed. if it failed without
// cancellation token is raised, then we do want to have watson report
cancellationToken.ThrowIfCancellationRequested();
// record reason why task got aborted. use NFW here since we don't want to
// crash VS on explicitly killing OOP.
task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed");
throw;
}
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册