public void Locked_PreventsLockUntilUnlocked() { AsyncContext.Run(async () => { var monitor = new AsyncMonitor(); var task1HasLock = new TaskCompletionSource(); var task1Continue = new TaskCompletionSource(); Task<IDisposable> initialLockTask = null; var task1 = Task.Run(async () => { initialLockTask = monitor.EnterAsync(); using (await initialLockTask) { task1HasLock.SetResult(); await task1Continue.Task; } }); await task1HasLock.Task; var lockTask = monitor.EnterAsync(); Assert.IsFalse(lockTask.IsCompleted); task1Continue.SetResult(); await lockTask; }); }
public void AsyncLock_Locked_PreventsLockUntilUnlocked() { AsyncContext.Run(async () => { var mutex = new AsyncLock(); var task1HasLock = new TaskCompletionSource(); var task1Continue = new TaskCompletionSource(); Task<IDisposable> task1LockTask = null; var task1 = Task.Run(async () => { task1LockTask = mutex.LockAsync(); using (await task1LockTask) { task1HasLock.SetResult(); await task1Continue.Task; } }); await task1HasLock.Task; Task<IDisposable> task2LockTask = null; var task2Start = Task.Factory.StartNew(async () => { task2LockTask = mutex.LockAsync(); await task2LockTask; }); var task2 = await task2Start; Assert.IsFalse(task2.IsCompleted); task1Continue.SetResult(); await task2; }); }
public void AsyncLock_Locked_PreventsLockUntilUnlocked() { Test.Async(async () => { var mutex = new AsyncLock(); var task1HasLock = new TaskCompletionSource(); var task1Continue = new TaskCompletionSource(); var task1 = TaskShim.Run(async () => { using (await mutex.LockAsync()) { task1HasLock.SetResult(); await task1Continue.Task; } }); await task1HasLock.Task; var task2Start = Task.Factory.StartNew(async () => { await mutex.LockAsync(); }); var task2 = await task2Start; Assert.IsFalse(task2.IsCompleted); task1Continue.SetResult(); await task2; }); }
public static Task InvokeAsync([NotNull] this IDispatcherService service, [NotNull] Func<Task> action) { Guard.NotNull(service, nameof(service)); Guard.NotNull(action, nameof(action)); var tcs = new TaskCompletionSource(); service.InvokeAsync(new Action(() => { action().ContinueWith(t => { if (t.Exception != null) { tcs.TrySetException(t.Exception); return; } if (t.IsCanceled) { tcs.TrySetCanceled(); } tcs.TrySetResult(); }); })); return tcs.Task; }
public void ProgressReport_NotifiesChangeOnCapturedSynchronizationContext() { Test.Async(async () => { SynchronizationContext updateContext = null; SynchronizationContext threadContext = null; var tcs = new TaskCompletionSource(); using (var thread = new AsyncContextThread()) { threadContext = await thread.Factory.Run(() => SynchronizationContext.Current); PropertyProgress<int> propertyProgress = await thread.Factory.Run(() => new PropertyProgress<int>()); propertyProgress.PropertyChanged += (_, e) => { updateContext = SynchronizationContext.Current; tcs.SetResult(); }; IProgress<int> progress = propertyProgress; progress.Report(13); await tcs.Task; } Assert.IsNotNull(updateContext); Assert.AreEqual(threadContext, updateContext); }); }
/// <summary> /// Creates an async-compatible barrier. /// </summary> /// <param name="participants">The number of participants.</param> public AsyncBarrier(int participants) { _sync = new object(); _tcs = new TaskCompletionSource(); _participants = _count = participants; //Enlightenment.Trace.AsyncBarrier_PhaseChanged(this, 0, participants, _tcs.Task); }
public void SetExceptions_FaultsTask() { var e = new[] { new InvalidOperationException() }; var tcs = new TaskCompletionSource(); tcs.SetException(e); Assert.IsTrue(tcs.Task.IsFaulted); Assert.IsTrue(tcs.Task.Exception.InnerExceptions.SequenceEqual(e)); }
/// <summary> /// Creates an async-compatible manual-reset event. /// </summary> /// <param name="set">Whether the manual-reset event is initially set or unset.</param> public AsyncManualResetEvent(bool set) { _sync = new object(); _tcs = new TaskCompletionSource(); if (set) { //Enlightenment.Trace.AsyncManualResetEvent_Set(this, _tcs.Task); _tcs.SetResult(); } }
private static Task<string> GetSomeTextAsync() { // https://msdn.microsoft.com/en-us/library/hh873177(v=vs.110).aspx var tcs = new TaskCompletionSource<string>(); tcs.SetResult("some text"); return tcs.Task; }
public void TrySetException_FaultsTask() { var e = new InvalidOperationException(); var tcs = new TaskCompletionSource(); tcs.TrySetException(e); Assert.IsTrue(tcs.Task.IsFaulted); Assert.AreSame(e, tcs.Task.Exception.InnerException); }
public void ConstructorWithStateAndOptions_SetsAsyncStateAndOptions() { var state = new object(); var options = TaskCreationOptions.AttachedToParent; var tcs = new TaskCompletionSource(state, options); Assert.AreSame(state, tcs.Task.AsyncState); Assert.AreEqual(options, tcs.Task.CreationOptions); }
public void SignalAndWaitAsync_Underflow_ThrowsException() { var tcs = new TaskCompletionSource(); var barrier = new AsyncBarrier(1, async _ => { await tcs.Task; }); barrier.SignalAndWaitAsync(); AssertEx.ThrowsException<InvalidOperationException>(() => barrier.SignalAndWaitAsync()); tcs.SetResult(); }
public void FromTask_ReturnsTokenWithoutCancellationRequested() { var tcs = new TaskCompletionSource(); var result = CancellationTokenHelpers.FromTask(tcs.Task); Assert.IsTrue(result.Token.CanBeCanceled); Assert.IsFalse(result.Token.IsCancellationRequested); }
public void TryCompleteFromCompletedTaskTResult_PropagatesCancellation() { Test.Async(async () => { var tcs = new TaskCompletionSource<int>(); tcs.TryCompleteFromCompletedTask(TaskConstants<int>.Canceled); await AssertEx.ThrowsExceptionAsync<OperationCanceledException>(() => tcs.Task); }); }
public void TryCompleteFromCompletedTask_PropagatesResult() { AsyncContext.Run(async () => { var tcs = new TaskCompletionSource(); tcs.TryCompleteFromCompletedTask(TaskConstants.Completed); await tcs.Task; }); }
public void TryCompleteFromCompletedTask_PropagatesCancellation() { AsyncContext.Run(async () => { var tcs = new TaskCompletionSource(); tcs.TryCompleteFromCompletedTask(TaskConstants.Canceled); await AssertEx.ThrowsExceptionAsync<OperationCanceledException>(() => tcs.Task); }); }
public void FromTaskSynchronously_TaskCompletes_TokenGetsCancellationRequested() { var tcs = new TaskCompletionSource(); var result = CancellationTokenHelpers.FromTask(tcs.Task, TaskContinuationOptions.ExecuteSynchronously); tcs.SetResult(); Assert.IsTrue(result.Token.CanBeCanceled); Assert.IsTrue(result.Token.IsCancellationRequested); }
public void TryCompleteFromCompletedTaskTResult_PropagatesResult() { Test.Async(async () => { var tcs = new TaskCompletionSource<int>(); tcs.TryCompleteFromCompletedTask(TaskConstants.Int32NegativeOne); var result = await tcs.Task; Assert.AreEqual(-1, result); }); }
/// <summary> /// Returns a <see cref="Task"/> that is canceled when this <see cref="CancellationToken"/> is canceled. This method will leak resources if the cancellation token is long-lived; use <see cref="ToCancellationTokenTaskSource"/> for a similar approach with proper resource management. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor.</param> /// <returns>A <see cref="Task"/> that is canceled when this <see cref="CancellationToken"/> is canceled.</returns> public static Task AsTask(this CancellationToken cancellationToken) { if (!cancellationToken.CanBeCanceled) return TaskConstants.Never; if (cancellationToken.IsCancellationRequested) return TaskConstants.Canceled; var tcs = new TaskCompletionSource(); cancellationToken.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: false); return tcs.Task; }
public void TryCompleteFromCompletedTask_WithDifferentTResult_PropagatesResult() { AsyncContext.Run(async () => { var tcs = new TaskCompletionSource<object>(); tcs.TryCompleteFromCompletedTask(TaskConstants.Int32NegativeOne); var result = await tcs.Task; Assert.AreEqual(-1, result); }); }
private Task SynchronouslyEndingOperation() { Synchronous.Log("Entered synchronously ending operation"); Thread.Sleep(100); var tcs = new TaskCompletionSource(); tcs.SetResult(); Synchronous.Log("Leaving synchronously ending operation"); return tcs.Task; }
public void TryCompleteFromCompletedTaskTResult_PropagatesException() { AsyncContext.Run(async () => { var source = new TaskCompletionSource<int>(); source.TrySetException(new NotImplementedException()); var tcs = new TaskCompletionSource<int>(); tcs.TryCompleteFromCompletedTask(source.Task); await AssertEx.ThrowsExceptionAsync<NotImplementedException>(() => tcs.Task); }); }
private async Task<FacebookAuthenticationResult> getFacebookToken() { var token = Xamarin.Facebook.AccessToken.CurrentAccessToken; if (token != null) return new FacebookAuthenticationResult(){ Token = token }; var completion = new TaskCompletionSource<FacebookAuthenticationResult>(); var loginCallback = new FacebookCallback(completion); var activity = Xamarin.Forms.Forms.Context as MainActivity; LoginManager.Instance.RegisterCallback (activity.CallbackManager, loginCallback); LoginManager.Instance.LogInWithReadPermissions(activity, new string[] { "public_profile", "email", "user_friends" }); return await completion.Task; }
/// <summary> /// Wraps a <see cref="Task"/> into the Begin method of an APM pattern. /// </summary> /// <param name="task">The task to wrap.</param> /// <param name="callback">The callback method passed into the Begin method of the APM pattern.</param> /// <param name="state">The state passed into the Begin method of the APM pattern.</param> /// <returns>The asynchronous operation, to be returned by the Begin method of the APM pattern.</returns> public static IAsyncResult ToBegin(Task task, AsyncCallback callback, object state) { var tcs = new TaskCompletionSource(state); task.ContinueWith(t => { tcs.TryCompleteFromCompletedTask(t); if (callback != null) callback(tcs.Task); }, TaskScheduler.Default); return tcs.Task; }
public static async Task ConfigureTopologyAsync(this Link @this, Func<ILinkTopologyConfig, Task> configure, CancellationToken cancellationToken) { var completion = new TaskCompletionSource(); if (cancellationToken.IsCancellationRequested) { completion.TrySetCanceled(); await completion.Task; return; } using (@this.CreateTopologyConfigurator(configure, () => { completion.TrySetResultWithBackgroundContinuations(); return Task.FromResult((object) null); }, ex => { completion.TrySetExceptionWithBackgroundContinuations(ex); return Task.FromResult((object) null); })) { IDisposable registration = null; try { registration = cancellationToken.Register(() => { completion.TrySetCanceledWithBackgroundContinuations(); }); } catch (ObjectDisposedException) { // Cancellation source already disposed } if (cancellationToken.IsCancellationRequested) { completion.TrySetCanceledWithBackgroundContinuations(); } try { await completion.Task .ConfigureAwait(false); } finally { registration?.Dispose(); } } }
public void Pulse_ReleasesOneWaiter() { AsyncContext.Run(async () => { var monitor = new AsyncMonitor(); int completed = 0; var task1Ready = new TaskCompletionSource(); var task2Ready = new TaskCompletionSource(); Task<IDisposable> lockTask1 = null; Task waitTask1 = null; var task1 = Task.Run(async () => { lockTask1 = monitor.EnterAsync(); using (await lockTask1) { waitTask1 = monitor.WaitAsync(); task1Ready.SetResult(); await waitTask1; Interlocked.Increment(ref completed); } }); await task1Ready.Task; Task<IDisposable> lockTask2 = null; Task waitTask2 = null; var task2 = Task.Run(async () => { lockTask2 = monitor.EnterAsync(); using (await lockTask2) { waitTask2 = monitor.WaitAsync(); task2Ready.SetResult(); await waitTask2; Interlocked.Increment(ref completed); } }); await task2Ready.Task; Task<IDisposable> lockTask3 = monitor.EnterAsync(); using (await lockTask3) { monitor.Pulse(); } await Task.WhenAny(task1, task2); var result = Interlocked.CompareExchange(ref completed, 0, 0); Assert.AreEqual(1, result); }); }
public void AsyncLazy_Start_CallsFunc() { AsyncContext.Run(async () => { var tcs = new TaskCompletionSource(); Func<int> func = () => { tcs.SetResult(); return 13; }; var lazy = new AsyncLazy<int>(func); lazy.Start(); await tcs.Task; }); }
/// <summary> /// Creates a task for the specified cancellation token, registering with the token if necessary. /// </summary> /// <param name="cancellationToken">The cancellation token to observe.</param> public CancellationTokenTaskSource(CancellationToken cancellationToken) { if (!cancellationToken.CanBeCanceled) { Task = TaskConstants.Never; return; } if (cancellationToken.IsCancellationRequested) { Task = TaskConstants.Canceled; return; } var tcs = new TaskCompletionSource(); _registration = cancellationToken.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: false); Task = tcs.Task; }
public async Task ExecuteAsync() { tcs = new TaskCompletionSource(); try { logUri = await logSharingService.ShareCurrentLogAsync(); DataTransferManager.ShowShareUI(); } catch (Exception ex) { ExceptionHandlingHelper.HandleNonFatalError(ex, "Unexpected exception occured while trying to share the log files."); } await tcs.Task; }
static async Task<int> AsyncMain() { mainTaskCompletionSource = new TaskCompletionSource<int>(); Console.CancelKeyPress += (s, e) => Terminate(); if (string.IsNullOrEmpty(Settings.Default.TelegramApiKey)) { Console.WriteLine( "You need to open 'FeedDotNetBot.exe.config.xml' and put your Telegram API key in there"); Terminate(1, false); return await mainTaskCompletionSource.Task; } else { Console.WriteLine("API Key: {0}", Settings.Default.TelegramApiKey); Console.WriteLine("Press CTRL + C to exit"); return await run(); } }
/// <summary> /// Creates an async-compatible countdown event. /// </summary> /// <param name="count">The number of signals this event will need before it becomes set. Must be greater than zero.</param> public AsyncCountdownEvent(int count) { _tcs = new TaskCompletionSource <int>(); _count = count; //Enlightenment.Trace.AsyncCountdownEvent_CountChanged(this, -1, count); }