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 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 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 static AsyncCallback Callback(Action<IAsyncResult> endMethod, TaskCompletionSource<object> tcs) { return asyncResult => { try { endMethod(asyncResult); tcs.TrySetResult(null); } catch (OperationCanceledException) { tcs.TrySetCanceled(); } catch (Exception ex) { tcs.TrySetException(ex); } }; }
/// <summary> /// Speak back text /// </summary> /// <param name="text">Text to speak</param> /// <param name="queue">If you want to chain together speak command or cancel current</param> /// <param name="crossLocale">Locale of voice</param> /// <param name="pitch">Pitch of voice</param> /// <param name="speechRate">Speak Rate of voice (All) (0.0 - 2.0f)</param> /// <param name="volume">Volume of voice (iOS/WP) (0.0-1.0)</param> public async Task SpeakAsync(string text, bool queue= false, CrossLocale? crossLocale = null, float? pitch = null , float? speechRate = null, float? volume= null) { if(!queue) { if(_lockAsync != null) { (await _lockAsync).Dispose(); } } _lockAsync = _mutex.LockAsync(); using (await _lockAsync) { if (string.IsNullOrWhiteSpace(text)) return; if (_speechSynthesizer == null) { Init(); } var localCode = string.Empty; //nothing fancy needed here if (pitch == null && speechRate == null && volume == null) { if (crossLocale.HasValue && !string.IsNullOrWhiteSpace(crossLocale.Value.Language)) { localCode = crossLocale.Value.Language; var voices = from voice in SpeechSynthesizer.AllVoices where (voice.Language == localCode && voice.Gender.Equals(VoiceGender.Female)) select voice; _speechSynthesizer.Voice = (voices.Any() ? voices.ElementAt(0) : SpeechSynthesizer.DefaultVoice); _element.Language = crossLocale.Value.Language; } else { _speechSynthesizer.Voice = SpeechSynthesizer.DefaultVoice; } } else { _element.PlaybackRate = speechRate.Value; _element.Volume = volume.Value; } try { var stream = await _speechSynthesizer.SynthesizeTextToStreamAsync(text); _element.SetSource(stream, stream.ContentType); _element.MediaEnded += (s, e) => _tcs.TrySetResult(null); _element.MediaFailed += (s, e) => _tcs.TrySetException(new Exception(e.ErrorMessage)); _element.Play(); await _tcs.Task; _tcs = new TaskCompletionSource<object>(); } catch (Exception ex) { Debug.WriteLine("Unable to playback stream: " + ex); _tcs.TrySetException(new Exception(ex.Message)); } } }
private static Task<string> DumpWebPageAsync(WebClient client, Uri uri) { //si utilizza TaskCompletionSource che gestisce un task figlio var tcs = new TaskCompletionSource<string>(); DownloadStringCompletedEventHandler handler = null; handler = (sender, args) => { client.DownloadStringCompleted -= handler; if (args.Cancelled) tcs.TrySetCanceled(); else if (args.Error != null) tcs.TrySetException(args.Error); else tcs.TrySetResult(args.Result); }; client.DownloadStringCompleted += handler; client.DownloadStringAsync(uri); return tcs.Task; }
public void TryCompleteFromCompletedTask_PropagatesException() { Test.Async(async () => { var source = new TaskCompletionSource(); source.TrySetException(new NotImplementedException()); var tcs = new TaskCompletionSource(); tcs.TryCompleteFromCompletedTask(source.Task); await AssertEx.ThrowsExceptionAsync<NotImplementedException>(() => tcs.Task); }); }
public void TrySetExceptions_FaultsTask() { var e = new[] { new InvalidOperationException() }; var tcs = new TaskCompletionSource(); tcs.TrySetException(e); Assert.IsTrue(tcs.Task.IsFaulted); Assert.IsTrue(tcs.Task.Exception.InnerExceptions.SequenceEqual(e)); }
/// <summary> /// Attempts to transition the underlying <see cref="Task"/> into the <see cref="TaskStatus.Faulted"/> state. /// </summary> /// <param name="exception">The exception to bind to this <see cref="Task"/>. May not be <c>null</c>.</param> /// <returns><c>true</c> if the operation was successful; otherwise, <c>false</c>.</returns> public bool TrySetException(Exception exception) { return(_tcs.TrySetException(exception)); }