public TClient GetClient(TOptions options, TokenCredential tokenCredential) { _cachedException?.Throw(); if (_cachedClient != null) { return(_cachedClient); } lock (_cacheLock) { _cachedException?.Throw(); if (_cachedClient != null) { return(_cachedClient); } try { _cachedClient = _factory(options, tokenCredential); } catch (Exception e) { _cachedException = ExceptionDispatchInfo.Capture(e); throw; } return(_cachedClient); } }
public async Task <bool> MoveNextAsync() { _exception?.Throw(); if (_valueQueue.TryDequeue(out var value)) { Current = value; return(true); } if (IsCompleted) { return(false); } _nextSource = new TaskCompletionSource <bool>(); await _nextSource.Task; if (!_valueQueue.TryDequeue(out value)) { return(!IsCompleted); } Current = value; return(true); }
public void Start(Action onTimeout) { lock (this) { _edi?.Throw(); _timeoutHappened = onTimeout; _timer.Change(TimeoutPeriod, TimeoutPeriod); } }
public void Start(Action onTimeout) { lock (this) { _edi?.Throw(); if (onTimeout == _timeoutHappened) { Defer(_currentLeader); return; } _timeoutHappened = onTimeout; _timer.Change(TimeoutPeriod, TimeoutPeriod); } }
private async Task <object[]> GetParameters(ObjectMethodExecutor executor, HttpRequest request) { //short circuit if no parameters if (executor.MethodParameters == null || executor.MethodParameters.Length == 0) { return(Array.Empty <object>()); } // loop through binders, in order // first suitable binder wins // so the order of registration is important ExceptionDispatchInfo lastException = null; try { return(await _parameterBinder.BindParameters(executor.MethodParameters, request)); } catch (Exception ex) { // continue on next suitable binder // but keep the exception when no other suitable binders are found lastException = ExceptionDispatchInfo.Capture(ex); } lastException?.Throw(); return(Array.Empty <object>()); }
private async Task ReadAttributeByType(GATTAttributeType attributeType, int timeoutMs) { Debug.WriteLine($"Discovering characteristics of type: {attributeType}"); _uuidOfAttributeBeingRead = attributeType; await _bgApi.ATTClientReadByTypeAsync( ConnectionHandle, StartATTHandle, EndATTHandle, BitConverter.GetBytes((UInt16)_uuidOfAttributeBeingRead) ).ConfigureAwait(false); using (var cancel = new CancellationTokenSource(timeoutMs)) { try { await _procedureCompletedWaitHandle .WaitAsync(cancel.Token) .ConfigureAwait(false); _exceptionToRethrow?.Throw(); } catch (OperationCanceledException) { throw new TimeoutException($"Timeout occured while discovering characteristics of type: {attributeType}"); } } }
private static void RunTestAsync(Func <Task> testAsync) { ExceptionDispatchInfo edi = null; var t = new Thread((o) => { var d = Dispatcher.CurrentDispatcher; var op = d.InvokeAsync(async() => { try { await testAsync(); } finally { d.InvokeShutdown(); } }); Dispatcher.Run(); if (op.Result.Exception != null) { edi = ExceptionDispatchInfo.Capture(op.Result.Exception.GetBaseException()); } }); t.SetApartmentState(ApartmentState.STA); t.Name = "AsyncTest TestHarness"; t.Start(); t.Join(); edi?.Throw(); }
/// <summary> /// Executes the result operation of the action method asynchronously writing the <see cref="Value"/> to the response. /// </summary> /// <param name="context">The context in which the result is executed.</param> /// <returns>An asynchronous operation.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="context"/> is <see langword="null"/>.</exception> public override async Task ExecuteResultAsync(ActionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } HttpResponse response = context.HttpContext.Response; ExceptionDispatchInfo exceptionDispatchInfo = null; try { await response.WriteJsonAsync( this.StatusCode.GetValueOrDefault((int)HttpStatusCode.OK), this.Value, this.SerializerSettings); } catch (Exception ex) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex); } finally { exceptionDispatchInfo?.Throw(); } }
protected async Task EnableMethodsAsync(CancellationToken ct) { ExceptionDispatchInfo exInfo = null; _mMethod.ScheduleTime = null; _mMethod.OperationType = TelemetryMetrics.DeviceOperationMethodEnable; _swMethod.Restart(); try { Task t = _dc.SetMethodHandlerAsync(TestMethodName, MethodHandlerAsync, null); _mMethod.ScheduleTime = _swMethod.ElapsedMilliseconds; _swMethod.Restart(); await t.ConfigureAwait(false); } catch (Exception ex) { _mMethod.ErrorMessage = $"{ex.GetType().Name} - {ex.Message}"; exInfo = ExceptionDispatchInfo.Capture(ex); } _mMethod.ExecuteTime = _swMethod.ElapsedMilliseconds; await _writer.WriteAsync(_mMethod).ConfigureAwait(false); exInfo?.Throw(); }
protected async Task SendMessageAsync(CancellationToken ct) { ExceptionDispatchInfo exInfo = null; _m.OperationType = TelemetryMetrics.DeviceOperationSend; _m.ScheduleTime = null; _sw.Restart(); try { Client.Message message = new Client.Message(_messageBytes); Task t = _dc.SendEventAsync(message, ct); _m.ScheduleTime = _sw.ElapsedMilliseconds; _sw.Restart(); await t.ConfigureAwait(false); } catch (Exception ex) { _m.ErrorMessage = $"{ex.GetType().Name} - {ex.Message}"; exInfo = ExceptionDispatchInfo.Capture(ex); } _m.ExecuteTime = _sw.ElapsedMilliseconds; await _writer.WriteAsync(_m).ConfigureAwait(false); exInfo?.Throw(); }
/// <summary> /// Enqueue the command to be eventually executed. If the command implements /// IDisposable, the command will be disposed after it is run and a tx is committed. /// </summary> public async ValueTask <bool> Enqueue(MergedTransactionCommand cmd) { _edi?.Throw(); _operations.Enqueue(cmd); _waitHandle.Set(); if (_concurrentOperations.TryAddCount() == false) { ThrowTxMergerWasDisposed(); } try { await cmd.TaskCompletionSource.Task; } finally { try { _concurrentOperations.Signal(); // done with this } catch (InvalidOperationException) { // Expected: "Invalid attempt made to decrement the event's count below zero." } } return(true); }
public static T RunOnDispatcherThreadSync <T>(Func <T> func, CancellationToken cancellationToken = default, Dispatcher dispatcher = null) { dispatcher ??= App.Current.MainWindow.Dispatcher; if (dispatcher.CheckAccess()) { return(func()); } ExceptionDispatchInfo exceptionDispatchInfo = null; T result = default(T); dispatcher.InvokeAsync(() => { try { result = func(); } catch (Exception ex) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex); } }, DispatcherPriority.Normal, cancellationToken).Task.Wait(cancellationToken); exceptionDispatchInfo?.Throw(); return(result); }
public void InsertDocuments() { Console.WriteLine("Setting up a lazy xml files reader that yields packages..."); var packages = nugetDumpReader.GetPackages(); Console.Write("Indexing documents into Elasticsearch..."); var waitHandle = new CountdownEvent(1); var bulkAll = elasticClient.BulkAll(packages, b => b .BackOffRetries(2) .BackOffTime("30s") .RefreshOnCompleted(true) .MaxDegreeOfParallelism(4) .Size(1000) ); ExceptionDispatchInfo captureInfo = null; bulkAll.Subscribe(new BulkAllObserver( onNext: b => Console.Write("."), onError: e => { captureInfo = ExceptionDispatchInfo.Capture(e); waitHandle.Signal(); }, onCompleted: () => waitHandle.Signal() )); waitHandle.Wait(); captureInfo?.Throw(); Console.WriteLine($"Done."); }
protected async Task RetryAsync(Func <Task> action, CancellationToken cancellationToken) { var succeeded = false; ExceptionDispatchInfo lastExceptionDispatchInfo = null; for (var i = 0; i < _retriesCount + 1 && cancellationToken.IsCancellationRequested == false; i++) { try { await action(); succeeded = true; break; } catch (Exception e) { lastExceptionDispatchInfo = ExceptionDispatchInfo.Capture(e); } if (i != _retriesCount - 1) { await Task.Delay(_retryInitialTimeout, cancellationToken); } } if (succeeded == false) { lastExceptionDispatchInfo?.Throw(); } }
public void Rollback() { if (_disposed) { throw new ObjectDisposedException("SessionConnectionCollection"); } if (_completed) { throw new InvalidOperationException("Not possible to call Commit or Rollback more than once on a SessionConnectionCollection"); } ExceptionDispatchInfo lastError = null; foreach (var conn in InitializedConnections.Values) { try { IDbTransaction tran; if (_transactions.TryGetValue(conn, out tran)) { tran.Rollback(); tran.Dispose(); } } catch (Exception e) { lastError = ExceptionDispatchInfo.Capture(e); } } _transactions.Clear(); _completed = true; lastError?.Throw(); }
public void RollBack() { ExceptionDispatchInfo lastError = null; if (!_isDisposed) { foreach (var context in _instantiatedDbContextCollection.Values) { try { if (_instantiatedDbContextTransaction.TryGetValue(context, out var transaction)) { transaction.Rollback(); transaction.Dispose(); } } catch (Exception exception) { lastError = ExceptionDispatchInfo.Capture(exception); } } } lastError?.Throw(); // Re-throw while maintaining the exception's original stack track _committed = true; }
internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, object state) { Debug.Assert(threadPoolThread == Thread.CurrentThread); CheckThreadPoolAndContextsAreDefault(); // ThreadPool starts on Default Context so we don't need to save the "previous" state as we know it is Default (null) if (executionContext != null && executionContext.m_isDefault) { // Default is a null ExecutionContext internally executionContext = null; } else if (executionContext != null) { // Non-Default context to restore threadPoolThread.ExecutionContext = executionContext; if (executionContext.HasChangeNotifications) { // There are change notifications; trigger any affected OnValuesChanged(previousExecutionCtx: null, executionContext); } } ExceptionDispatchInfo edi = null; try { callback.Invoke(state); } catch (Exception ex) { // Note: we have a "catch" rather than a "finally" because we want // to stop the first pass of EH here. That way we can restore the previous // context before any of our callers' EH filters run. edi = ExceptionDispatchInfo.Capture(ex); } // Enregister threadPoolThread as it crossed EH, and use enregistered variable Thread currentThread = threadPoolThread; ExecutionContext currentExecutionCtx = currentThread.ExecutionContext; // Restore changed SynchronizationContext back to Default currentThread.SynchronizationContext = null; if (currentExecutionCtx != null) { // The EC always needs to be reset for this overload, as it will flow back to the caller if it performs // extra work prior to returning to the Dispatch loop. For example for Task-likes it will flow out of await points // Restore to Default before Notifications, as the change can be observed in the handler. currentThread.ExecutionContext = null; if (currentExecutionCtx.HasChangeNotifications) { // There are change notifications; trigger any affected OnValuesChanged(currentExecutionCtx, nextExecutionCtx: null); } } // If exception was thrown by callback, rethrow it now original contexts are restored edi?.Throw(); }
private static async Task <Maybe <T> > ConvertNext <T>(Task <bool> task, object state) { ExceptionDispatchInfo edi = null; var _enumerator = (IAsyncEnumerator <T>)state; try { var hasNext = await task; if (hasNext) { return(new Maybe <T>(_enumerator.Current)); } } catch (Exception e) { edi = ExceptionDispatchInfo.Capture(e); } // First dispose the enumerator. // Ensure that if an exception was thrown // by MoveNext() and Dispose throw we do not // swallow it. await _enumerator.DisposeAsync(edi?.SourceException); edi?.Throw(); return(default(Maybe <T>)); }
public void Dispose() { _classificationsReady1.Dispose(); _classificationsReady2.Dispose(); _view.Dispose(); _excInfo?.Throw(); }
public async Task BlindCommand(byte[] cmd) { ExceptionDispatchInfo capturedException = null; var wasOpen = _port.IsOpen; try { if (!wasOpen) { OpenPort(); } await _port.BaseStream.WriteAsync(cmd, 0, cmd.Length); // Waits for writing completed while (_port.BytesToWrite > 0) { await Task.Delay(50); } } catch (Exception ex) { capturedException = ExceptionDispatchInfo.Capture(ex); } if (!wasOpen) { await ClosePort(); } capturedException?.Throw(); }
public static TcpListener GetRandomPortListener(IPAddress address, out int port, int minimumPort = 49152, int maximumPort = 65536, bool randomStart = true) { ExceptionDispatchInfo edi = null; int range = maximumPort - minimumPort; if (range <= 0) { throw new ArgumentException("maximumPort must be larger than minimumPort"); } int start = randomStart ? _freePortRandom.Next(range) : 0; for (int i = 0; i < range; ++i) { port = (i + start) % range + minimumPort; Debug.Assert(port >= minimumPort && port <= maximumPort); var listener = new TcpListener(address, port); try { listener.Start(); return(listener); } catch (Exception ex) { edi = ExceptionDispatchInfo.Capture(ex); } } edi?.Throw(); throw new InvalidOperationException("No free ports"); }
public static T RunOnDispatcherThreadSync <T>(Func <T> func, CancellationToken cancellationToken = default(CancellationToken), CoreDispatcher dispatcher = null) { if (dispatcher == null) { dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; } if (dispatcher.HasThreadAccess) { return(func()); } ExceptionDispatchInfo exceptionDispatchInfo = null; T result = default(T); dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { try { result = func(); } catch (Exception ex) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex); } }).AsTask(cancellationToken).Wait(cancellationToken); exceptionDispatchInfo?.Throw(); return(result); }
protected async Task ReceiveMessageAsync(CancellationToken ct) { ExceptionDispatchInfo exInfo = null; _mRecv.ScheduleTime = null; _swRecv.Restart(); try { Task <Client.Message> t = _dc.ReceiveAsync(ct); _mRecv.ScheduleTime = _swRecv.ElapsedMilliseconds; _swRecv.Restart(); Client.Message msg = await t.ConfigureAwait(false); await _dc.CompleteAsync(msg).ConfigureAwait(false); int deviceIdFromMessage = BitConverter.ToInt32(msg.GetBytes()); if (_id != deviceIdFromMessage) { throw new InvalidOperationException($"DeviceId mismatch: Expected {_id} actual {deviceIdFromMessage}."); } } catch (Exception ex) { _mRecv.ErrorMessage = $"{ex.GetType().Name} - {ex.Message}"; exInfo = ExceptionDispatchInfo.Capture(ex); } _mRecv.ExecuteTime = _swRecv.ElapsedMilliseconds; await _writer.WriteAsync(_mRecv).ConfigureAwait(false); exInfo?.Throw(); }
protected async Task OpenServiceClientAsync(CancellationToken ct) { ExceptionDispatchInfo exInfo = null; _m.OperationType = TelemetryMetrics.ServiceOperationOpen; _m.ScheduleTime = null; _sw.Restart(); try { Task t = s_sc.OpenAsync(); _m.ScheduleTime = _sw.ElapsedMilliseconds; _sw.Restart(); await t.ConfigureAwait(false); } catch (Exception ex) { _m.ErrorMessage = ex.Message; exInfo = ExceptionDispatchInfo.Capture(ex); } _m.ExecuteTime = _sw.ElapsedMilliseconds; await _writer.WriteAsync(_m).ConfigureAwait(false); exInfo?.Throw(); }
protected async Task WaitForMethodAsync(CancellationToken ct) { ExceptionDispatchInfo exInfo = null; _mMethod.ScheduleTime = null; _mMethod.OperationType = TelemetryMetrics.DeviceOperationMethodCalled; _swMethod.Restart(); try { Task t = _methodSemaphore.WaitAsync(ct); _mMethod.ScheduleTime = _swMethod.ElapsedMilliseconds; _swMethod.Restart(); await t.ConfigureAwait(false); } catch (Exception ex) { _mMethod.ErrorMessage = $"{ex.GetType().Name} - {ex.Message}"; exInfo = ExceptionDispatchInfo.Capture(ex); } _mMethod.ExecuteTime = _swMethod.ElapsedMilliseconds; await _writer.WriteAsync(_mMethod).ConfigureAwait(false); exInfo?.Throw(); }
/// <summary> /// Ensures that if a specified object is a <see cref="Task"/>, it is properly awaited and if it is a <see cref="Task{TResult}"/>, the result is retrieved /// </summary> /// <param name="potentialTask">The object that may be a <see cref="Task"/> or <see cref="Task{TResult}"/></param> /// <returns>The result of the task once it is complete if <paramref name="potentialTask"/> is a <see cref="Task{TResult}"/>; or, <paramref name="potentialTask"/> once it is complete if <paramref name="potentialTask"/> is a <see cref="Task"/>; otherwise, <paramref name="potentialTask"/> (immediately)</returns> public static async Task <object> ResolveAsync(object potentialTask) { if (potentialTask is Task task) { ExceptionDispatchInfo edi = default; await task.ContinueWith(t => { if (t.IsFaulted) { edi = ExceptionDispatchInfo.Capture(t.Exception); } else { var type = t.GetType(); if (type.IsConstructedGenericType) { potentialTask = taskValueGetters.GetOrAdd(type, CreateTaskValueGetter).Invoke(t); } } }).ConfigureAwait(false); edi?.Throw(); } return(potentialTask); }
protected async Task CallMethodAsync(CancellationToken ct) { ExceptionDispatchInfo exInfo = null; _mMethod.ScheduleTime = null; _mMethod.OperationType = TelemetryMetrics.ServiceOperationMethodCall; _swMethod.Restart(); try { var methodCall = new CloudToDeviceMethod(TestMethodName); Task t = s_sc.InvokeDeviceMethodAsync(Configuration.Stress.GetDeviceNameById(_id, _authType), methodCall); _mMethod.ScheduleTime = _swMethod.ElapsedMilliseconds; _swMethod.Restart(); await t.ConfigureAwait(false); } catch (Exception ex) { _mMethod.ErrorMessage = ex.Message; exInfo = ExceptionDispatchInfo.Capture(ex); } _mMethod.ExecuteTime = _swMethod.ElapsedMilliseconds; await _writer.WriteAsync(_mMethod).ConfigureAwait(false); exInfo?.Throw(); }
protected virtual void Dispose(bool disposing) { ExceptionDispatchInfo?exception = null; for (int i = 0; i < 5; i++) { try { RemoveReadOnlyAttributes(); _rootDirectory.Delete(true); return; } catch (IOException ex) { if (!_rootDirectory.Exists) { // Somehow the directory has already // been removed. Our job here is done. return; } exception = ExceptionDispatchInfo.Capture(ex); // Something still has a lock on a file // in the directory. Wait a bit and try again. Thread.Sleep(1000); } } exception?.Throw(); }
protected async Task SendMessageAsync(CancellationToken ct) { ExceptionDispatchInfo exInfo = null; _m.OperationType = TelemetryMetrics.ServiceOperationSend; _m.ScheduleTime = null; _sw.Restart(); try { var message = new Message(_messageBytes); Task t = s_sc.SendAsync(Configuration.Stress.GetDeviceNameById(_id, _authType), message); _m.ScheduleTime = _sw.ElapsedMilliseconds; _sw.Restart(); await t.ConfigureAwait(false); } catch (Exception ex) { _m.ErrorMessage = ex.Message; exInfo = ExceptionDispatchInfo.Capture(ex); } _m.ExecuteTime = _sw.ElapsedMilliseconds; await _writer.WriteAsync(_m).ConfigureAwait(false); exInfo?.Throw(); }
private async Task StartCopyStreamAsyncHelper(long? copyLength, long? maxLength, CancellationToken token) { if (copyLength.HasValue && maxLength.HasValue) { throw new ArgumentException("Cannot specify both copyLength and maxLength."); } if (src.CanSeek && maxLength.HasValue && src.Length - src.Position > maxLength) { throw new InvalidOperationException("The length of the stream exceeds the permitted length."); } if (src.CanSeek && copyLength.HasValue && src.Length - src.Position < copyLength) { throw new ArgumentOutOfRangeException("copyLength", "The requested number of bytes exceeds the length of the stream remaining from the specified position."); } token.ThrowIfCancellationRequested(); byte[] readBuff2 = new byte[buffSize]; byte[] writeBuff2 = new byte[buffSize]; int count = CalculateBytesToCopy(copyLength, 0L); int num = await src.ReadAsync(readBuff2, 0, count, token).ConfigureAwait(continueOnCapturedContext: false); long totalBytes = num; CheckMaxLength(maxLength, totalBytes); byte[] array = readBuff2; readBuff2 = writeBuff2; writeBuff2 = array; ExceptionDispatchInfo readException = null; while (num > 0) { token.ThrowIfCancellationRequested(); Task task = dest.WriteAsync(writeBuff2, 0, num, token); count = CalculateBytesToCopy(copyLength, totalBytes); Task<int> readTask = null; if (count > 0) { try { readTask = src.ReadAsync(readBuff2, 0, count, token); } catch (Exception source) { readException = ExceptionDispatchInfo.Capture(source); } } else { readTask = Task.FromResult(0); } await task.ConfigureAwait(continueOnCapturedContext: false); readException?.Throw(); num = await readTask.WithCancellation(token).ConfigureAwait(continueOnCapturedContext: false); totalBytes += num; CheckMaxLength(maxLength, totalBytes); array = readBuff2; readBuff2 = writeBuff2; writeBuff2 = array; } if (copyLength.HasValue && totalBytes != copyLength.Value) { throw new ArgumentOutOfRangeException("copyLength", "The requested number of bytes exceeds the length of the stream remaining from the specified position."); } }