public static void TaskExGenericFromExceptionIsFaulted() { var exception = new Exception(); var task = TaskExEx.FromException <bool>(exception); Assert.IsTrue(task.IsFaulted); }
private static async Task <bool> WaitPrivateAsync(SemaphoreSlim semaphore, int millisecondsTimeout, CancellationToken cancellationToken) { if (semaphore.Wait(0)) { return(true); } var start = ThreadingHelper.TicksNow(); var timeout = millisecondsTimeout; while ( timeout > 0 && await TaskExEx.FromWaitHandleInternal ( semaphore.AvailableWaitHandle, timeout, cancellationToken ).ConfigureAwait(false) ) { if (semaphore.Wait(0)) { return(true); } timeout = (int)(millisecondsTimeout - ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start)); } return(false); }
public static void TaskExGenericFromExceptionRespectsException() { var exception = new Exception(); var task = TaskExEx.FromException <bool>(exception); // ReSharper disable once PossibleNullReferenceException Assert.AreEqual(exception, task.Exception.InnerException); }
public static void TaskExGenericFromCanceledIsCanceled() { using (var source = new CancellationTokenSource()) { source.Cancel(); var task = TaskExEx.FromCanceled <bool>(source.Token); Assert.IsTrue(task.IsCanceled); } }
public Task <bool> WaitAsync(int millisecondsTimeout, CancellationToken cancellationToken) { var state = GetState(); if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } if (cancellationToken.IsCancellationRequested) { return(TaskExEx.FromCanceled <bool>(cancellationToken)); } var source = new TaskCompletionSource <bool>(); if (state.CanEnter.Wait(0, cancellationToken) && TryOffset(-1, out var dummy, state)) { source.SetResult(true); return(source.Task); } RootedTimeout.Launch ( () => { try { source.SetResult(false); } catch (InvalidCastException exception) { // Already canceled No.Op(exception); } }, () => { try { source.SetCanceled(); } catch (InvalidOperationException exception) { // Already timeout No.Op(exception); } }, millisecondsTimeout, cancellationToken ); state.AsyncWaiters.Add(source); return(source.Task); }
private static async Task <bool> WaitPrivateAsync(SemaphoreSlim semaphore) { if (semaphore.Wait(0)) { return(true); } while (true) { await TaskExEx.FromWaitHandleInternal(semaphore.AvailableWaitHandle).ConfigureAwait(false); if (semaphore.Wait(0)) { return(true); } } }
private static async Task <bool> WaitPrivateAsync(SemaphoreSlim semaphore, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (semaphore.Wait(0)) { return(true); } while (true) { await TaskExEx.FromWaitHandleInternal(semaphore.AvailableWaitHandle, cancellationToken).ConfigureAwait(false); if (semaphore.Wait(0)) { return(true); } } }
public static void TaskExGenericFromCanceledThrowsOnNonCanceledToken() { Assert.Throws <ArgumentOutOfRangeException, Task <bool> >(() => TaskExEx.FromCanceled <bool>(CancellationToken.None)); }