#pragma warning disable CA1801 // async parameter unused on netstandard private async ValueTask ProcessAsync(HttpMessage message, bool async) #pragma warning restore CA1801 { using HttpRequestMessage httpRequest = BuildRequestMessage(message); SetPropertiesOrOptions <HttpMessage>(httpRequest, MessageForServerCertificateCallback, message); HttpResponseMessage responseMessage; Stream?contentStream = null; try { #if NET5_0_OR_GREATER if (!async) { // Sync HttpClient.Send is not supported on browser but neither is the sync-over-async // HttpClient.Send would throw a NotSupported exception instead of GetAwaiter().GetResult() // throwing a System.Threading.SynchronizationLockException: Cannot wait on monitors on this runtime. #pragma warning disable CA1416 // 'HttpClient.Send(HttpRequestMessage, HttpCompletionOption, CancellationToken)' is unsupported on 'browser' responseMessage = Client.Send(httpRequest, HttpCompletionOption.ResponseHeadersRead, message.CancellationToken); #pragma warning restore CA1416 } else #endif { #pragma warning disable AZC0110 // DO NOT use await keyword in possibly synchronous scope. responseMessage = await Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, message.CancellationToken) #pragma warning restore AZC0110 // DO NOT use await keyword in possibly synchronous scope. .ConfigureAwait(false); } if (responseMessage.Content != null) { #if NET5_0_OR_GREATER if (async) { contentStream = await responseMessage.Content.ReadAsStreamAsync(message.CancellationToken).ConfigureAwait(false); } else { contentStream = responseMessage.Content.ReadAsStream(message.CancellationToken); } #else #pragma warning disable AZC0110 // DO NOT use await keyword in possibly synchronous scope. contentStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false); #pragma warning restore AZC0110 // DO NOT use await keyword in possibly synchronous scope. #endif } } // HttpClient on NET5 throws OperationCanceledException from sync call sites, normalize to TaskCanceledException catch (OperationCanceledException e) when(CancellationHelper.ShouldWrapInOperationCanceledException(e, message.CancellationToken)) { throw CancellationHelper.CreateOperationCanceledException(e, message.CancellationToken); } catch (HttpRequestException e) { throw new RequestFailedException(e.Message, e); } message.Response = new PipelineResponse(message.Request.ClientRequestId, responseMessage, contentStream); }
void SearchCriteriaChanged(object sender, EventArgs e) { CancellationHelper.CancelAndDispose(ref _Bar._cancellationSource, true); _Menu.ItemsSource = null; _Menu.Symbols.Clear(); var s = _FinderBox.Text; if (s.Length == 0) { ShowNamespaceAndTypeMenu(); return; } try { switch (_ScopeBox.Filter) { case ScopeType.ActiveDocument: FindInDocument(s); break; case ScopeType.ActiveProject: FindInProject(s); break; } _Menu.RefreshSymbols(); _Menu.UpdateLayout(); } catch (OperationCanceledException) { // ignores cancellation } catch (ObjectDisposedException) { } }
private async Task RetryAsync(Exception exception, bool async, CancellationToken cancellationToken) { // Depending on the timing, the stream can be closed as a result of cancellation when the transport closes the stream. // If the user requested cancellation, we translate to TaskCanceledException, similar to what we do HttpWebRequestTransport. if (exception is ObjectDisposedException) { CancellationHelper.ThrowIfCancellationRequested(cancellationToken); } bool isNonCustomerCancelledException = exception is OperationCanceledException && !cancellationToken.IsCancellationRequested; if (!_responseClassifier.IsRetriableException(exception) && !isNonCustomerCancelledException) { ExceptionDispatchInfo.Capture(exception).Throw(); } if (_exceptions == null) { _exceptions = new List <Exception>(); } _exceptions.Add(exception); _retryCount++; if (_retryCount > _maxRetries) { throw new AggregateException($"Retry failed after {_retryCount} tries", _exceptions); } _currentStream.Dispose(); _currentStream = EnsureStream(async ? (await _asyncStreamFactory(_position).ConfigureAwait(false)) : _streamFactory(_position)); }
private async ValueTask ProcessInternal(HttpMessage message, bool async) { var request = CreateRequest(message.Request); ServicePointHelpers.SetLimits(request.ServicePoint); using var registration = message.CancellationToken.Register(state => ((HttpWebRequest)state).Abort(), request); try { if (message.Request.Content != null) { using var requestStream = async ? await request.GetRequestStreamAsync().ConfigureAwait(false) : request.GetRequestStream(); if (async) { await message.Request.Content.WriteToAsync(requestStream, message.CancellationToken).ConfigureAwait(false); } else { message.Request.Content.WriteTo(requestStream, message.CancellationToken); } } else { // match the behavior of HttpClient if (message.Request.Method != RequestMethod.Head && message.Request.Method != RequestMethod.Get && message.Request.Method != RequestMethod.Delete) { request.ContentLength = 0; } request.ContentType = null; } WebResponse webResponse; try { webResponse = async ? await request.GetResponseAsync().ConfigureAwait(false) : request.GetResponse(); } // HttpWebRequest throws for error responses catch that catch (WebException exception) when(exception.Response != null) { webResponse = exception.Response; } message.Response = new HttpWebResponseImplementation(message.Request.ClientRequestId, (HttpWebResponse)webResponse); } // ObjectDisposedException might be thrown if the request is aborted during the content upload via SSL catch (ObjectDisposedException) when(message.CancellationToken.IsCancellationRequested) { CancellationHelper.ThrowIfCancellationRequested(message.CancellationToken); } catch (WebException webException) { // WebException is thrown in the case of .Abort() call CancellationHelper.ThrowIfCancellationRequested(message.CancellationToken); throw new RequestFailedException(0, webException.Message, webException); } }
public void Cancel() { Assert.True(CancellationHelper.Cancel(ref _cts)); Assert.Same(_cts, CancellationHelper.Cancelled); Assert.False(CancellationHelper.Cancel(ref _cts)); }
public void Replace_After_Cancel() { Assert.True(CancellationHelper.Cancel(ref _cts)); var cts = new CancellationTokenSource(); Assert.False(CancellationHelper.Replace(ref _cts, cts)); Assert.True(cts.IsCancellationRequested); }
public void Release() { if (--_refCount == 0) { _buffer.Changed -= OnChanged; //Stop and blow away the old scan (even if it didn't finish, the results are not interesting anymore). CancellationHelper.CancelAndDispose(ref _Cancellation, false); _root = null; //Allow the old root to be GC'd } }
public void CreateOperationCanceledExceptionPassesTokenOnSupportedVersions() { using var cts = new CancellationTokenSource(); cts.Cancel(); var ex = (TaskCanceledException)CancellationHelper.CreateOperationCanceledException(new Exception("test"), cts.Token); #if NETCOREAPP2_1_OR_GREATER Assert.IsTrue(ex.CancellationToken.IsCancellationRequested); #else Assert.IsFalse(ex.CancellationToken.IsCancellationRequested); #endif }
void ViewClosed(object sender, EventArgs e) { CancellationHelper.CancelAndDispose(ref _Cancellation, false); _ToolBarTray.ToolBars.Clear(); _ToolBarTray.MouseEnter -= ToolBarMouseEnter; _ToolBarTray.MouseLeave -= ToolBarMouseLeave; View.Selection.SelectionChanged -= ViewSelectionChanged; View.VisualElement.MouseMove -= ViewMouseMove; View.VisualElement.PreviewKeyUp -= ViewKeyUp; //View.LayoutChanged -= ViewLayoutChanged; View.Closed -= ViewClosed; Config.Updated -= ConfigUpdated; }
async void OnTagsChanged(object sender, EventArgs e) { try { CancellationHelper.CancelAndDispose(ref _Element._Cancellation, true); await Task.Run(TagDocument, _Element._Cancellation.GetToken()); } catch (ObjectDisposedException) { return; } catch (OperationCanceledException) { return; } _Element.InvalidateVisual(); }
async Task ScanBufferAsync(ITextSnapshot snapshot) { //Stop and blow away the old scan (even if it didn't finish, the results are not interesting anymore). CancellationHelper.CancelAndDispose(ref _Cancellation, true); var cancellationToken = _Cancellation.GetToken(); //The underlying buffer could be very large, meaning that doing the scan for all matches on the UI thread //is a bad idea. Do the scan on the background thread and use a callback to raise the changed event when //the entire scan has completed. _root = await ParseAsync(snapshot, cancellationToken); //This delegate is executed on a background thread. await Task.Run(() => TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length))), cancellationToken); }
/// <summary>Throws a cancellation exception if cancellation has been requested via <paramref name="originalToken"/> or <paramref name="timeoutToken"/>.</summary> /// <param name="originalToken">The customer provided token.</param> /// <param name="timeoutToken">The linked token that is cancelled on timeout provided token.</param> /// <param name="inner">The inner exception to use.</param> /// <param name="timeout">The timeout used for the operation.</param> #pragma warning disable CA1068 // Cancellation token has to be the last parameter internal static void ThrowIfCancellationRequestedOrTimeout(CancellationToken originalToken, CancellationToken timeoutToken, Exception?inner, TimeSpan timeout) #pragma warning restore CA1068 { CancellationHelper.ThrowIfCancellationRequested(originalToken); if (timeoutToken.IsCancellationRequested) { throw CancellationHelper.CreateOperationCanceledException( inner, timeoutToken, $"The operation was cancelled because it exceeded the configured timeout of {timeout:g}. " + $"Network timeout can be adjusted in {nameof(ClientOptions)}.{nameof(ClientOptions.Retry)}.{nameof(RetryOptions.NetworkTimeout)}."); } }
void SearchCriteriaChanged(object sender, EventArgs e) { CancellationHelper.CancelAndDispose(ref _Bar._cancellationSource, true); ClearItems(); var s = _FinderBox.Text; if (s.Length == 0) { AddNamespaceAndTypes(); return; } try { switch (_ScopeBox.Filter) { case ScopeType.ActiveDocument: FindInDocument(s); break; case ScopeType.ActiveProject: FindInProject(s); break; } } catch (OperationCanceledException) { // ignores cancellation } catch (ObjectDisposedException) { } }
void ViewSelectionChanged(object sender, EventArgs e) { // suppress event handler if KeepToolBar if (DateTime.Now < _LastExecute.AddSeconds(1)) { return; } if (View.Selection.IsEmpty) { _ToolBarTray.Visibility = Visibility.Hidden; View.VisualElement.MouseMove -= ViewMouseMove; CancellationHelper.CancelAndDispose(ref _Cancellation, true); _SelectionStatus = 0; return; } if (Interlocked.CompareExchange(ref _SelectionStatus, Selecting, 0) != 0) { return; } CancellationHelper.CancelAndDispose(ref _Cancellation, true); CreateToolBar(_Cancellation.Token); async void CreateToolBar(CancellationToken token) { try { await Task.Delay(400, token); if (token.IsCancellationRequested == false) { await CreateToolBarAsync(token); } } catch (OperationCanceledException) { // ignore } } }
async void HandleClick(object sender, RoutedEventArgs e) { CancellationHelper.CancelAndDispose(ref _Bar._cancellationSource, true); if (_Menu != null && _Bar._SymbolList == _Menu) { _Bar.HideMenu(); return; } if (Node.IsTypeDeclaration() == false) { var span = Node.FullSpan; if (span.Contains(_Bar._SemanticContext.Position) && Node.SyntaxTree.FilePath == _Bar._SemanticContext.Document.FilePath) { _Bar._View.SelectNode(Node, Keyboard.Modifiers != ModifierKeys.Control); } else { Node.GetIdentifierToken().GetLocation().GoToSource(); } return; } if (_Menu == null) { _Menu = new SymbolList { Container = _Bar._SymbolListContainer }; _Menu.Header = new WrapPanel { Orientation = Orientation.Horizontal, Children = { new ThemedButton(new ThemedMenuText(Node.GetDeclarationSignature(), true) .SetGlyph(ThemeHelper.GetImage(Node.GetImageId())), null, () => _Bar._SemanticContext.RelocateDeclarationNode(Node).GetLocation().GoToSource()) { BorderThickness = WpfHelper.TinyMargin, Margin = WpfHelper.SmallHorizontalMargin, Padding = WpfHelper.SmallHorizontalMargin, }, (_FilterBox = new MemberFilterBox(_Menu)), } }; _Menu.Footer = new TextBlock { Margin = WpfHelper.MenuItemMargin } .ReferenceProperty(TextBlock.ForegroundProperty, EnvironmentColors.SystemGrayTextBrushKey); _Bar.SetupSymbolListMenu(_Menu); await AddItemsAsync(Node, _Bar._cancellationSource.GetToken()); if (_Menu.Symbols.Count > 100) { ScrollViewer.SetCanContentScroll(_Menu, true); } } else { ((TextBlock)_Menu.Footer).Clear(); await RefreshItemsAsync(Node, _Bar._cancellationSource.GetToken()); } var footer = (TextBlock)_Menu.Footer; if (Config.Instance.NaviBarOptions.MatchFlags(NaviBarOptions.CodeStatistics)) { if (_PartialCount > 1) { footer.Append(ThemeHelper.GetImage(KnownImageIds.OpenDocumentFromCollection)) .Append(_PartialCount); } footer.Append(ThemeHelper.GetImage(KnownImageIds.Code)) .Append(_Bar._View.TextSnapshot.GetLineSpan(Node.Span).Length); footer.Visibility = Visibility.Visible; } else { footer.Visibility = Visibility.Collapsed; } _Menu.ItemsControlMaxHeight = _Bar._View.ViewportHeight / 2; _Bar.ShowMenu(this, _Menu); _FilterBox?.FocusTextBox(); }
void ViewClosed(object sender, EventArgs e) { _View.Selection.SelectionChanged -= Update; CancellationHelper.CancelAndDispose(ref _cancellationSource, false); _View.Closed -= ViewClosed; }
async void Update(object sender, EventArgs e) { HideMenu(); CancellationHelper.CancelAndDispose(ref _cancellationSource, true); var cs = _cancellationSource; if (cs != null) { try { await Update(cs.Token); } catch (OperationCanceledException) { // ignore } } async Task Update(CancellationToken token) { var nodes = await UpdateModelAsync(token); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(token); var c = Math.Min(Items.Count, nodes.Count); int i, i2; for (i = 1, i2 = 0; i < c && i2 < c; i2++) { var n = nodes[i2]; if (token.IsCancellationRequested) { return; } var n2 = (Items[i] as NodeItem).Node; if (n2 == n) { // keep the NaviItem if node is not updated ++i; continue; } if (n.IsKind(SyntaxKind.NamespaceDeclaration)) { continue; } break; } if ((i == 1 || i2 < nodes.Count && nodes[i2].IsTypeOrNamespaceDeclaration()) && _RootItem.FilterText.Length == 0) { // clear type and namespace menu items if a type is changed _RootItem.ClearSymbolList(); } c = Items.Count; while (c > i) { Items.RemoveAt(--c); } c = nodes.Count; while (i2 < c) { if (token.IsCancellationRequested) { return; } var node = nodes[i2]; if (node.IsKind(SyntaxKind.NamespaceDeclaration)) { _RootItem.SetText(node.GetDeclarationSignature()); ++i2; continue; } bool highlight = node.IsMemberDeclaration(); var newItem = new NodeItem(this, node); if (highlight) { newItem.FontWeight = FontWeights.Bold; newItem.IsChecked = true; } Items.Add(newItem); ++i2; } } }