public Task StopAsync() { if (0 != this._isDisposed) { return(TplTaskExtensions.CompletedTask); } this._refreshTimer.Cancel(); bool lockTaken = false; object obj; CancellationTokenSource cancellationTokenSource; SignalTask signalTask; try { Monitor.Enter(obj = this._segmentLock, ref lockTaken); this._isRunning = false; cancellationTokenSource = this._abortTokenSource; signalTask = this._readTask; } finally { if (lockTaken) { Monitor.Exit(obj); } } CancellationTokenExtensions.CancelSafe(cancellationTokenSource); return(signalTask.WaitAsync()); }
public void Register(IRefactoring refactoring) { Contract.Requires(refactoring != null); var context = this; try { CancellationTokenExtensions.SetCancellationToken(context._originalContext.CancellationToken); var newRoot = refactoring.ComputeRoot(context.Root); var document = context.Document.WithSyntaxRoot(newRoot); if (ProducedEquivalent(context.Root, newRoot)) { document = context.Document; } var codeAction = CodeAction.Create(refactoring.Description, async c => document); _originalContext.RegisterRefactoring(codeAction); } catch (OperationCanceledException) { throw; } catch (Exception) { if (Settings.Instance.CanThrow) { throw; } // TODO: add logging } }
public void GetAwaiter_WithCancel_IsCompleted() { CancellationTokenSource tokenSource = new CancellationTokenSource(); var awaiter = CancellationTokenExtensions.GetAwaiter(tokenSource.Token); Assert.False(awaiter.IsCompleted); tokenSource.Cancel(); Assert.True(awaiter.IsCompleted); }
protected virtual void Dispose(bool disposing) { if (!disposing) { return; } this._mediaSourceTaskCompletionSource.TrySetCanceled(); CancellationTokenExtensions.CancelDisposeSafe(this._playingCancellationTokenSource); }
private async Task <TypeSyntax> GetVariableType(VariableDeclaratorSyntax variable) { var type = _variableDeclaration.Type; if (type.IsVar) { var model = await _document.GetSemanticModelAsync(CancellationTokenExtensions.GetCancellationToken()); type = model .GetSpeculativeExpressionType(variable.Initializer.Value) .ToTypeSyntax(); } return(type); }
private void ResetCancellationToken() { Debug.WriteLine("SmMediaManager.ResetCancellationToken()"); if (this._closeCancellationTokenSource.IsCancellationRequested) { CancellationTokenExtensions.CancelDisposeSafe(this._closeCancellationTokenSource); this._closeCancellationTokenSource = new CancellationTokenSource(); } if (!this._playbackCancellationTokenSource.IsCancellationRequested) { return; } CancellationTokenExtensions.CancelDisposeSafe(this._playbackCancellationTokenSource); this._playbackCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(this._closeCancellationTokenSource.Token); }
public virtual Task <long> ReadAsync(CancellationToken cancellationToken) { CancellationTokenSource cancellationTokenSource = (CancellationTokenSource)null; TaskCompletionSource <long> completionSource1 = (TaskCompletionSource <long>)null; bool lockTaken = false; object obj; TaskCompletionSource <long> completionSource2; try { Monitor.Enter(obj = this._readerLock, ref lockTaken); Debug.Assert(this._readerTask == null || this._readerTask.IsCompleted); if (this._isClosed) { return(TaskEx.FromResult <long>(0L)); } if (this._readCancellationSource == null || this._readCancellationSource.IsCancellationRequested) { cancellationTokenSource = this._readCancellationSource; this._readCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); } if (this._readResultTask.Task.IsCompleted) { completionSource1 = this._readResultTask; this._readResultTask = new TaskCompletionSource <long>(); } completionSource2 = this._readResultTask; CancellationToken token = this._readCancellationSource.Token; this._readerTask = TaskEx.Run((Func <Task>)(() => this.ReadSegmentsAsync(token)), token); } finally { if (lockTaken) { Monitor.Exit(obj); } } if (null != completionSource1) { completionSource1.TrySetCanceled(); } if (null != cancellationTokenSource) { CancellationTokenExtensions.CancelDisposeSafe(cancellationTokenSource); } return(completionSource2.Task); }
public static IEnumerable <SyntaxNode> GetThisAndParents(this SyntaxNode node, int?limit = null) { while (node != null) { CancellationTokenExtensions.ThrowOnCancellation(); if (limit < 0) { break; } yield return(node); node = node.Parent; limit = limit - 1; } }
public static bool NeedInject(InjectParameter parameter, ConstructorDeclarationSyntax constructor) { Contract.Requires(parameter != null); Contract.Requires(constructor != null); var fieldName = parameter.Name; var assigments = constructor.Body?.DescendantNodes().OfType <AssignmentExpressionSyntax>().ToList(); foreach (var assigment in assigments.WhileOk()) { if (assigment.GetAssigneeName(allowThisAccess: true) == fieldName) { return(false); } } return(!CancellationTokenExtensions.IsCancellationRequested()); }
protected virtual void Dispose(bool disposing) { if (!disposing) { return; } try { this.Close(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } bool lockTaken = false; object obj; Task task; CancellationTokenSource cancellationTokenSource; try { Monitor.Enter(obj = this._readerLock, ref lockTaken); task = this._readerTask; this._readerTask = TplTaskExtensions.CompletedTask; cancellationTokenSource = this._readCancellationSource; this._readCancellationSource = (CancellationTokenSource)null; } finally { if (lockTaken) { Monitor.Exit(obj); } } if (null != task) { TaskCollector.Default.Add(task, "CallbackReader.Close"); } if (null == cancellationTokenSource) { return; } CancellationTokenExtensions.CancelDisposeSafe(cancellationTokenSource); }
public virtual Task <long> ReadAsync(CancellationToken cancellationToken) { CancellationTokenSource cancellationTokenSource = null; TaskCompletionSource <long> completionSource1 = null; TaskCompletionSource <long> completionSource2; lock (_readerLock) { Debug.Assert(_readerTask == null || _readerTask.IsCompleted); if (_isClosed) { return(TaskEx.FromResult(0L)); } if (_readCancellationSource == null || _readCancellationSource.IsCancellationRequested) { cancellationTokenSource = _readCancellationSource; _readCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); } if (_readResultTask.Task.IsCompleted) { completionSource1 = _readResultTask; _readResultTask = new TaskCompletionSource <long>(); } completionSource2 = _readResultTask; CancellationToken token = _readCancellationSource.Token; _readerTask = TaskEx.Run(() => ReadSegmentsAsync(token), token); } if (null != completionSource1) { completionSource1.TrySetCanceled(); } if (null != cancellationTokenSource) { CancellationTokenExtensions.CancelDisposeSafe(cancellationTokenSource); } return(completionSource2.Task); }
private async Task ReadResponseAsync(IMediaParser mediaParser, IWebStreamResponse webStreamResponse, WebResponse webResponse, SingleStreamMediaManager.QueueThrottle throttle, CancellationToken cancellationToken) { byte[] buffer = new byte[16384]; Task cancellationTask = CancellationTokenExtensions.AsTask(cancellationToken); try { ISegmentMetadata segmentMetadata = this._webMetadataFactory.CreateSegmentMetadata(webResponse, (ContentType)null); mediaParser.StartSegment(segmentMetadata); using (Stream stream = await webStreamResponse.GetStreamAsync(cancellationToken).ConfigureAwait(false)) { while (true) { Task waitTask = throttle.WaitAsync(); if (!waitTask.IsCompleted) { Task task = await TaskEx.WhenAny(waitTask, cancellationTask).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); } int length = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); if (length > 0) { mediaParser.ProcessData(buffer, 0, length); } else { break; } } } } finally { mediaParser.ProcessEndOfData(); } }
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext originalContext) { CancellationTokenExtensions.SetCancellationToken(originalContext.CancellationToken); if (originalContext.Document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } try { CompilationUnitSyntax root = (await originalContext .Document .GetSyntaxRootAsync(originalContext.CancellationToken) .ConfigureAwait(false)) .As <CompilationUnitSyntax>(); if (root != null && !originalContext.CancellationToken.IsCancellationRequested) { var node = GetNode(originalContext, root); if (node != null) { var newContext = new RefactoringContext(originalContext, root); ComputeRefactorings(newContext, node); await ComputeRefactoringsAsync(newContext, node); } } } catch (OperationCanceledException ex) { throw; } catch (Exception ex) { if (Settings.Instance.CanThrow) { throw; } // TODO: add logging } }
protected virtual void Dispose(bool disposing) { if (!disposing) { return; } try { Close(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } Task task; CancellationTokenSource cancellationTokenSource; lock (_readerLock) { task = _readerTask; _readerTask = TplTaskExtensions.CompletedTask; cancellationTokenSource = _readCancellationSource; _readCancellationSource = null; } if (null != task) { TaskCollector.Default.Add(task, "CallbackReader.Close"); } if (null == cancellationTokenSource) { return; } CancellationTokenExtensions.CancelDisposeSafe(cancellationTokenSource); }
private static CodeAction GetCodeAction( string title, Func <CompilationUnitSyntax, CancellationToken, Task <CompilationUnitSyntax> > getRoot, RefactoringContext context) { Contract.Requires(!string.IsNullOrWhiteSpace(title)); Contract.Requires(getRoot != null); return(CodeAction.Create(title, async c => { CancellationTokenExtensions.SetCancellationToken(context._originalContext.CancellationToken); var root = await context.Document.GetSyntaxRootAsync(c); try { var newRoot = await getRoot(root as CompilationUnitSyntax, c); if (ProducedEquivalent(root, newRoot)) { return context.Document; } return context.Document.WithSyntaxRoot(newRoot); } catch (OperationCanceledException) { throw; } catch (Exception) { if (Settings.Instance.CanThrow) { throw; } // TODO: add logging return context.Document; } })); }
private async Task SimplePlayAsync(ContentType contentType, IWebReader webReader, IWebStreamResponse webStreamResponse, WebResponse webResponse, TaskCompletionSource <bool> configurationTaskCompletionSource, CancellationToken cancellationToken) { try { this._mediaStreamConfigurator.Initialize(); this._mediaStreamConfigurator.MediaManager = (IMediaManager)this; IMediaParser mediaParser = await this._mediaParserFactory.CreateAsync((IMediaParserParameters) new MediaParserParameters(), contentType, cancellationToken).ConfigureAwait(false); if (null == mediaParser) { throw new NotSupportedException("Unsupported content type: " + (object)contentType); } this.State = MediaManagerState.Opening; EventHandler configurationComplete = (EventHandler)null; configurationComplete = (EventHandler)((sender, args) => { mediaParser.ConfigurationComplete -= configurationComplete; configurationTaskCompletionSource.TrySetResult(true); }); mediaParser.ConfigurationComplete += configurationComplete; using (IBufferingManager bufferingManager = this._bufferingManagerFactory()) { SingleStreamMediaManager.QueueThrottle throttle = new SingleStreamMediaManager.QueueThrottle(); bufferingManager.Initialize((IQueueThrottling)throttle, new Action(this._mediaStreamConfigurator.CheckForSamples)); mediaParser.Initialize(bufferingManager, (Action <IProgramStreams>)null); IStreamMetadata streamMetadata = this._webMetadataFactory.CreateStreamMetadata(webResponse, (ContentType)null); mediaParser.InitializeStream(streamMetadata); Task reader = (Task)null; try { using (webReader) { try { if (null == webStreamResponse) { webStreamResponse = await webReader.GetWebStreamAsync((Uri)null, false, cancellationToken, (Uri)null, new long?(), new long?(), webResponse).ConfigureAwait(false); } reader = this.ReadResponseAsync(mediaParser, webStreamResponse, webResponse, throttle, cancellationToken); Task task = await TaskEx.WhenAny((Task)configurationTaskCompletionSource.Task, CancellationTokenExtensions.AsTask(cancellationToken)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); await MediaStreamSourceExtensions.PlayAsync(this._mediaStreamConfigurator, (IEnumerable <IMediaParserMediaStream>) mediaParser.MediaStreams, new TimeSpan?(), cancellationToken).ConfigureAwait(false); this.State = MediaManagerState.Playing; await reader.ConfigureAwait(false); reader = (Task)null; } finally { if (null != webStreamResponse) { webStreamResponse.Dispose(); } } } } catch (OperationCanceledException ex) { } catch (Exception ex) { string message = ExceptionExtensions.ExtendedMessage(ex); Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() failed: " + message); this.SetMediaState(MediaManagerState.Error, message); } this.State = MediaManagerState.Closing; if (null != reader) { try { await reader.ConfigureAwait(false); } catch (OperationCanceledException ex) { } catch (Exception ex) { Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() reader failed: " + ExceptionExtensions.ExtendedMessage(ex)); } } mediaParser.ConfigurationComplete -= configurationComplete; mediaParser.EnableProcessing = false; mediaParser.FlushBuffers(); bufferingManager.Flush(); bufferingManager.Shutdown((IQueueThrottling)throttle); await this._mediaStreamConfigurator.CloseAsync().ConfigureAwait(false); } } catch (Exception ex) { Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() cleanup failed: " + ExceptionExtensions.ExtendedMessage(ex)); } this._mediaStreamConfigurator.MediaManager = (IMediaManager)null; if (!configurationTaskCompletionSource.Task.IsCompleted) { configurationTaskCompletionSource.TrySetCanceled(); } this.State = MediaManagerState.Closed; await this._reportStateTask.WaitAsync().ConfigureAwait(false); }
public void Dispose() { CancellationTokenExtensions.CancelDisposeAndClear(ref _cancellationTokenSource); }
private static bool HasBadKind(SemanticModel semanticModel, ExpressionSyntax node) { var kind = semanticModel.GetSymbolInfo(node, CancellationTokenExtensions.GetCancellationToken()).Symbol?.Kind; return(kind.HasValue && kind.Value == SymbolKind.NamedType); }