/// <summary> /// A helper method for mocking APM (classic) asynchronous methods with on TAP (modern) asynchronous methods. /// </summary> /// <remarks> /// This is based on <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx"/> /// and <a href="http://msdn.microsoft.com/en-us/library/hh873178.aspx"/>. /// </remarks> public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state) { Debug.Assert(task != null, "task"); var taskCompletionSource = new TaskCompletionSource<object>(state); task.ContinueWith( t => { if (t.IsFaulted) { taskCompletionSource.TrySetException(t.Exception.InnerExceptions); } else if (t.IsCanceled) { taskCompletionSource.TrySetCanceled(); } else { taskCompletionSource.SetResult(null); } if (callback != null) { callback(taskCompletionSource.Task); } }, TaskScheduler.Default); return taskCompletionSource.Task; }
public async void Should_Forward_Context_On_Rpc() { /* Setup */ var tcs = new TaskCompletionSource<bool>(); MessageContext firstContext = null; MessageContext secondContext = null; var requester = BusClientFactory.CreateDefault(); var firstResponder = BusClientFactory.CreateDefault(); var secondResponder = BusClientFactory.CreateDefault(); firstResponder.RespondAsync<FirstRequest, FirstResponse>(async (req, c) => { firstContext = c; var resp = await firstResponder.RequestAsync<SecondRequest, SecondResponse>(new SecondRequest(), c.GlobalRequestId); return new FirstResponse { Infered = resp.Source }; }); secondResponder.RespondAsync<SecondRequest, SecondResponse>((req, c) => { secondContext = c; tcs.SetResult(true); return Task.FromResult(new SecondResponse { Source = Guid.NewGuid() }); }); /* Test */ requester.RequestAsync<FirstRequest, FirstResponse>(); await tcs.Task; /* Assert */ Assert.Equal(firstContext.GlobalRequestId, secondContext.GlobalRequestId); }
private Task<string> GetStringAsycTaskCompletionSource(string url) { var tcs= new TaskCompletionSource<string>(); Func<string,string> getstring = GetString; try { getstring.BeginInvoke(url, (a) => { var result = getstring.EndInvoke(a); tcs.SetResult(result); }, null); } catch (Exception ex) { tcs.TrySetException(ex); } return tcs.Task; }
public Task<Socket> ConnectAsync(IPEndPoint remoteEndPoint) { _connectTcs = new TaskCompletionSource<Socket>(); var task = _connectTcs.Task; Connect(remoteEndPoint); return task; }
public void ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults() { // Arrange Mock<IAuthorizationFilter> mockAttr = new Mock<IAuthorizationFilter>() { CallBase = true }; HttpResponseMessage response = new HttpResponseMessage(); InvalidOperationException exception = new InvalidOperationException("test"); TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(response); tcs.TrySetException(exception); mockAttr.Setup(a => a.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task); Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object); Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromResult<HttpResponseMessage>(response); TestTraceWriter traceWriter = new TestTraceWriter(); AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockAttr.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAuthorizationFilterAsync" }, new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ExecuteAuthorizationFilterAsync" } }; // Act & Assert Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation); Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait()); // Assert Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationTokenSource cancellationToken) { processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; var tcs = new TaskCompletionSource<ProcessResults>(); var standardOutput = new List<string>(); var standardError = new List<string>(); var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; process.OutputDataReceived += (sender, args) => { if (args.Data != null) { standardOutput.Add(args.Data); } }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) { standardError.Add(args.Data); } }; cancellationToken.Token.ThrowIfCancellationRequested(); _log.Debug("Registering cancellation for " + cancellationToken.GetHashCode()); cancellationToken.Token.Register(() => { tcs.TrySetCanceled(); KillProcessAndChildren(process.Id); }); process.Exited += (sender, args) => { tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError)); }; if (process.Start() == false) { tcs.TrySetException(new InvalidOperationException("Failed to start process")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); return tcs.Task; }
public static Task<ResponseMessage> Execute(this WebClient client, RequestMessage requestMessage, Uri uri, string productName, TaskCompletionSource<string> tcs) { client.ShouldNotBeNull("client"); requestMessage.ShouldNotBeNull("requestMessage"); try { var responseText = ResolveRequestSerializer(productName).Serialize(requestMessage).Base64Encode(); return client .UploadStringTask(uri, "POST", responseText) .ContinueWith(task => { var responseBytes = task.Result; return ResolveResponseSerializer(productName).Deserialize(responseBytes.Base64Decode()); }); } catch(Exception ex) { if(log.IsErrorEnabled) log.ErrorException("WebClient를 통한 요청이 실패했습니다.", ex); throw; } }
public Task PlaySoundAsync(string filename) { // Create media player var player = new MediaPlayer(); // Create task completion source to support async/await var tcs = new TaskCompletionSource<bool> (); // Open the resource var fd = Xamarin.Forms.Forms.Context.Assets.OpenFd (filename); // Hook up some events player.Prepared += (s, e) => { player.Start(); }; player.Completion += (sender, e) => { tcs.SetResult(true); }; // Initialize player.SetDataSource (fd.FileDescriptor); player.Prepare (); return tcs.Task; }
public Task CopyToAsync(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } var tcs = new TaskCompletionSource<object>(); try { var task = this.SerializeToStreamAsync(stream); if (task == null) { throw new InvalidOperationException(); } task.ContinueWith(t => { if (t.IsFaulted) { tcs.TrySetException(t.Exception.GetBaseException()); return; } if (t.IsCanceled) { tcs.TrySetCanceled(); return; } tcs.TrySetResult(null); }); } catch (Exception ex) { tcs.TrySetException(ex); } return tcs.Task; }
/// <summary> /// Get the string by URI. /// </summary> /// <param name="requestUri">The Uri the request is sent to.</param> /// <returns>string</returns> public Task<string> GetStringAsync(Uri requestUri) { TaskCompletionSource<string> tcs = new TaskCompletionSource<string>(); try { this.DownloadStringCompleted += (s, e) => { if (e.Error == null) { tcs.TrySetResult(e.Result); } else { tcs.TrySetException(e.Error); } }; this.DownloadStringAsync(requestUri); } catch (Exception ex) { tcs.TrySetException(ex); } if (tcs.Task.Exception != null) { throw tcs.Task.Exception; } return tcs.Task; }
public Task<byte[]> ReadAsBufferAsync() { var tcs = new TaskCompletionSource<byte[]>(); try { Stream stream = new MemoryStream(); this.SerializeToStreamAsync(stream).ContinueWith(copyTask => { try { if (copyTask.IsFaulted) { stream.Dispose(); tcs.SetException(copyTask.Exception.GetBaseException()); } else { if (copyTask.IsCanceled) { stream.Dispose(); tcs.SetCanceled(); } else { stream.Seek(0, SeekOrigin.Begin); var buff = new byte[stream.Length]; Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buff, 0, buff.Length, null).ContinueWith(readTask => tcs.SetResult(buff)); } } } catch (Exception ex) { stream.Dispose(); tcs.SetException(ex); } }); } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task; }
internal static Task<Report> CreateReport(string projectPath, CancellationToken cancellationToken, IProgress<string> progress, ICodeInspectSettings codeInspectSettings) { TaskCompletionSource<Report> completedTask = new TaskCompletionSource<Report>(); try { if (cancellationToken.IsCancellationRequested) { completedTask.TrySetCanceled(); return completedTask.Task; } if (projectPath.EndsWith("xml")) { completedTask.TrySetResult(CreateReportFromXml(projectPath)); } else { return CreateReportFromProject( codeInspectSettings.InspectCodePath, projectPath, Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), DateTime.Now.Ticks + ".xml"), progress: progress); } } catch (Exception ex) { completedTask.TrySetException(ex); } return completedTask.Task; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(new HttpResponseMessage()); return tcs.Task; }
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsyncCore( HttpRequestMessage request, CancellationToken cancellationToken) { TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.Redirect; response.Headers.Location = new Uri(Location + Calls); response.RequestMessage = request; if (Calls == 1) { // First call the message should contain If-* headers Assert.That(request.RequestUri, Is.EqualTo(new Uri(Location))); Assert.That(request.Headers.IfMatch.Count == 1); Assert.That(request.Headers.IfNoneMatch.Count == 1); Assert.That(request.Headers.IfModifiedSince.HasValue); Assert.That(request.Headers.IfUnmodifiedSince.HasValue); } else { // After first call the message should not contain If-* headers Assert.That(request.RequestUri, Is.EqualTo(new Uri(Location + (Calls - 1)))); Assert.That(request.Headers.IfMatch.Count == 0); Assert.That(request.Headers.IfNoneMatch.Count == 0); Assert.IsNull(request.Headers.IfModifiedSince); Assert.IsNull(request.Headers.IfUnmodifiedSince); } tcs.SetResult(response); return tcs.Task; }
private void OnError(int? contextId, string error) { var exception = new InvalidOperationException(error); if (contextId == null || contextId == -1) { _projectContexts.TrySetException(exception); _shutdown.RequestShutdown(); } else { _compileResponses.AddOrUpdate(contextId.Value, _ => { var tcs = new TaskCompletionSource<CompileResponse>(); tcs.SetException(exception); return tcs; }, (_, existing) => { if (!existing.TrySetException(exception)) { var tcs = new TaskCompletionSource<CompileResponse>(); tcs.TrySetException(exception); return tcs; } return existing; }); } }
public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken) { if (processStartInfo == null) { throw new ArgumentNullException("processStartInfo"); } // force some settings in the start info so we can capture the output processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; processStartInfo.CreateNoWindow = true; var tcs = new TaskCompletionSource<ProcessResults>(); var standardOutput = new List<string>(); var standardError = new List<string>(); var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true, }; process.OutputDataReceived += (sender, args) => { if (args.Data != null) { standardOutput.Add(args.Data); } }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) { standardError.Add(args.Data); } }; process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError)); cancellationToken.Register(() => { tcs.TrySetCanceled(); process.CloseMainWindow(); }); cancellationToken.ThrowIfCancellationRequested(); if (process.Start() == false) { tcs.TrySetException(new InvalidOperationException("Failed to start process")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); return tcs.Task; }
private async Task<bool> SaveServerCreds(ServerCredentials configuration) { var tsc = new TaskCompletionSource<bool>(); Deployment.Current.Dispatcher.BeginInvoke(async () => { await Lock.WaitAsync(); try { var json = JsonConvert.SerializeObject(configuration); await _storageService.WriteAllTextAsync(Constants.Settings.ServerCredentialSettings, json).ConfigureAwait(false); } finally { Lock.Release(); } Debug.WriteLine("SaveCreds, Server count: " + (configuration != null && configuration.Servers != null ? configuration.Servers.Count : 0)); tsc.SetResult(true); }); return await tsc.Task; }
/// <summary> /// Check for simple binding parameters in POST data. Bind POST /// data as well as query string data /// </summary> /// <param name="metadataProvider"></param> /// <param name="actionContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { string stringValue = null; NameValueCollection col = TryReadBody(actionContext.Request); if (col != null) stringValue = col[Descriptor.ParameterName]; // try reading query string if we have no POST/PUT match if (stringValue == null) { var query = actionContext.Request.GetQueryNameValuePairs(); if (query != null) { var matches = query.Where(kv => kv.Key.ToLower() == Descriptor.ParameterName.ToLower()); var keyValuePairs = matches as IList<KeyValuePair<string, string>> ?? matches.ToList(); if (keyValuePairs.Any()) stringValue = keyValuePairs.First().Value; } } object value = StringToType(stringValue); // Set the binding result here SetValue(actionContext, value); // now, we can return a completed task with no result TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>(); tcs.SetResult(default(AsyncVoid)); return tcs.Task; }
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { try { var result = new TokenAuthenticator().Authenticate(actionContext, _authenticator); } catch (Exception e) { TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetException(e); return tcs.Task; } if (actionContext.Response != null) { TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(actionContext.Response); return tcs.Task; } else { return continuation().ContinueWith<HttpResponseMessage>((tsk) => { HttpResponseMessage response = tsk.Result; return response; }, TaskContinuationOptions.OnlyOnRanToCompletion); } }
private void OnPopupClosed(object sender, object e) { if (_tcs != null && !_tcs.Task.IsCompleted) _tcs.SetException(new OperationCanceledException()); // user closed the window _tcs = null; _popup = null; }
async Task<bool> SignIn() { var tcs = new TaskCompletionSource<bool> (); var alert = new UIAlertView ("Please sign in", "", null, "Cancel", "Ok"); alert.AlertViewStyle = UIAlertViewStyle.SecureTextInput; var tb = alert.GetTextField(0); tb.ShouldReturn = (t)=>{ alert.DismissWithClickedButtonIndex(1,true); signIn(tcs,tb.Text); return true; }; alert.Clicked += async (object sender, UIButtonEventArgs e) => { if(e.ButtonIndex == 0) { tcs.TrySetResult(false); alert.Dispose(); return; } var id = tb.Text; signIn(tcs,id); }; alert.Show (); return await tcs.Task; }
public Task<bool> RunMultipleTasksWithSingleResult() { var _result = new TaskCompletionSource<bool>(); var _arguments = new [] { new DoWorkArguments { Sequence = 1, SleepInterval = TimeSpan.FromMilliseconds(5000), ResultToReturn = false, ShouldThrowException = false }, new DoWorkArguments { Sequence = 2, SleepInterval = TimeSpan.FromMilliseconds(25), ResultToReturn = true, ShouldThrowException = true }, new DoWorkArguments { Sequence = 3, SleepInterval = TimeSpan.FromMilliseconds(50), ResultToReturn = true, ShouldThrowException = false } }; var _tasks = new List<Task<bool>>(); Parallel.ForEach(_arguments, argument => _tasks.Add(this.DoWork(argument))); Task.WhenAll(_tasks).ContinueWith(taskResults => { Console.WriteLine("{0:mm:ss.ffffff} [{1}] ---> Processing result ({2})", DateTime.Now, Thread.CurrentThread.ManagedThreadId, taskResults.Status); if (taskResults.IsFaulted) { _result.SetException(taskResults.Exception); } else { var _allGood = taskResults.Result.All(result => result); _result.SetResult(_allGood); } }); Console.WriteLine("{0:mm:ss.ffffff} [{1}] About to return task completion result", DateTime.Now, Thread.CurrentThread.ManagedThreadId); return _result.Task; }
public async Task IsEventEditableForTest() { var tcs = new TaskCompletionSource<Event>(); string userId = "u1"; string userId2 = "u2"; Guid e1Id = new Guid("00000000-0000-0000-0000-000000000000"); Guid e2Id = new Guid("00000000-0000-0000-0000-000000000001"); Event e1 = new Event { Id = e1Id, Title = "New Event", OthersCanEdit = true }; Event e2 = new Event { Id = e2Id, Title = "New Event2", OthersCanEdit = false, OrganizerId = userId }; tcs.SetResult(e1); _eventRepository.Setup(mock => mock.GetEventInfo(e1Id)).Returns(tcs.Task); var task = await _userService.IsEventEditableFor(e1Id, userId); _eventRepository.Verify(mock => mock.GetEventInfo(e1Id), Times.Once()); Assert.AreEqual(true, task, "This event should be editable, but the method IsEventEditable returns false."); var tcs2 = new TaskCompletionSource<Event>(); tcs2.SetResult(e2); _eventRepository.Setup(mock => mock.GetEventInfo(e2Id)).Returns(tcs2.Task); var task2 = await _userService.IsEventEditableFor(e2Id, userId); _eventRepository.Verify(mock => mock.GetEventInfo(e2Id), Times.Once(), "Method GetEventInfo was not called or was called more than once (or its parameters were wrong)."); Assert.AreEqual(true, task2, "This event should be editable, but the method IsEventEditable returns false."); _eventRepository.Setup(mock => mock.GetEventInfo(e2Id)).Returns(tcs2.Task); var task3 = await _userService.IsEventEditableFor(e2Id, userId2); _eventRepository.Verify(mock => mock.GetEventInfo(e2Id), Times.Exactly(2), "Method GetEventInfo was not called or was called more than once (or its parameters were wrong)."); Assert.AreEqual(false, task3, "This event should not be editable, but the method IsEventEditable returns true."); }
public async Task InteractDuringBrowse() { using (var debugSession = new DebugSession(_session)) { using (var sf = new SourceFile("x <- 'old'; browser()")) { var browse = new TaskCompletionSource<bool>(); debugSession.Browse += (s, e) => { browse.TrySetResult(true); }; await sf.Source(_session); await browse.Task; using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("x <- 'new'\n"); } REvaluationResult x; using (var eval = await _session.BeginEvaluationAsync()) { x = await eval.EvaluateAsync("x"); } x.StringResult.Should().Be("new"); } } }
public override IChannelHandler CreateNewInstance() { // TODO correct? shares references... var tcsRconResponse = new TaskCompletionSource<Message.Message>(_tcsRconResponse.Task.AsyncState); var tcsResponse = new TaskCompletionSource<Message.Message>(_tcsResponse.Task.AsyncState); return new RconInboundHandler(tcsRconResponse, tcsResponse); }
static int PICK_CONTACT_REQUEST = 42; // The request code protected void OnActivityResult(TaskCompletionSource<ContactInfo> tcs, ActivityResultEventArgs e) //int requestCode, Android.App.Result resultCode, Intent data) { // Check which request it is that we're responding to if (e.requestCode == PICK_CONTACT_REQUEST) { // Make sure the request was successful if (e.resultCode == Android.App.Result.Ok) { var loader = new CursorLoader(MainActivity.Instance, e.data.Data, projection, null, null, null); var cursor = (Android.Database.ICursor)loader.LoadInBackground(); var contactList = new List<ContactInfo>(); if (cursor.MoveToFirst()) { do { contactList.Add(GetContactInfoFromCursor(cursor)); } while (cursor.MoveToNext()); } tcs.SetResult(contactList.FirstOrDefault()); return; } } tcs.SetResult(null); }
private Task<bool> DoWork( DoWorkArguments arguments) { Console.WriteLine("{0:mm:ss.ffffff} [{1}] Doing work for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence); var _result = new TaskCompletionSource<bool>(); new Task(() => { Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Starting for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence); Thread.Sleep(arguments.SleepInterval); if (arguments.ShouldThrowException) { Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Sequence {2} is exceptional !", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence); var _exception = new ApplicationException("Bang !"); _result.SetException(_exception); } else { _result.SetResult(arguments.ResultToReturn); } Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Completed for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence); }).Start(); Console.WriteLine("{0:mm:ss.ffffff} [{1}] Exiting for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence); return _result.Task; }
public TaskSupervisor() { _stopping = new TaskCompletionSource<IStopEvent>(); _stoppingToken = new CancellationTokenSource(); _participants = new List<Participant>(); _stopToken = new CancellationTokenSource(); }
public void RunAsync_Cancel() { bool canComplete = false; IAsyncAction action = null; action = ThreadPool.RunAsync(a => { while (!canComplete) Thread.Sleep(10); }); var tcs = new TaskCompletionSource<AsyncStatus>(); action.Completed = (a, s) => { tcs.SetResult(s); }; action.Cancel(); Thread.Sleep(100); Assert.AreEqual(AsyncStatus.Canceled, action.Status); canComplete = true; Assert.IsTrue(SpinWait.SpinUntil(() => tcs.Task.IsCompleted, millisecondsTimeout: 400), "Task did not complete under 400ms."); Assert.AreEqual(AsyncStatus.Canceled, action.Status, "Task should not change status after cancel"); }
public BufferedItem(object payload) { _completionSource = new TaskCompletionSource <object>(); }
public async Task OnActive(IModel model, CancellationToken cancellation) { var newState = State; while (true) { if (cancellation.IsCancellationRequested) { newState = LinkTopologyState.Stopping; } ChangeState(newState); switch (State) { case LinkTopologyState.Init: newState = LinkTopologyState.Configuring; break; case LinkTopologyState.Configuring: case LinkTopologyState.Reconfiguring: newState = await OnConfigureAsync(model, State == LinkTopologyState.Reconfiguring, cancellation) .ConfigureAwait(false); break; case LinkTopologyState.Ready: _readyCompletion.TrySetResult(null); try { await cancellation.WaitCancellation() .ConfigureAwait(false); } finally { _readyCompletion = new TaskCompletionSource <object>(); } newState = LinkTopologyState.Stopping; break; case LinkTopologyState.Disposed: #pragma warning disable 4014 Task.Factory.StartNew(Dispose, TaskCreationOptions.LongRunning); #pragma warning restore 4014 return; case LinkTopologyState.Stopping: if (cancellation.IsCancellationRequested) { ChangeState(LinkTopologyState.Init); return; } newState = LinkTopologyState.Reconfiguring; return; default: throw new NotImplementedException($"Handler for state ${State} not implemeted"); } } }
private void cancelled(TaskCompletionSource <string> taskSource) { taskSource.TrySetCanceled(); }
private TaskCompletionSource <bool> CreateCompletion() { var task = new TaskCompletionSource <bool>(); return(task); }
public PrioritizerDisposable(CancellationToken cancellationToken) { _tcs = new TaskCompletionSource <int>(); _tcs.RegisterForCancellation(cancellationToken).UnregisterOnCompletion(_tcs.Task); }
public QueueItem(bool isAwaitable, CancellationToken cancellationToken) { _tcs = new TaskCompletionSource <IDisposable>(TaskCreationOptions.RunContinuationsAsynchronously); IsAwaitable = isAwaitable; _tcs.RegisterForCancellation(cancellationToken).UnregisterOnCompletion(_tcs.Task); }
private async Task <ProcessResult> ExecuteAsync(Process process) { int timeOutInMilliseconds = Convert.ToInt32(Timeout.TotalMilliseconds); var stdError = new StringBuilder(); var stdOutput = new StringBuilder(); var outputWaiter = new CountdownEvent(2); process.ErrorDataReceived += (_, e) => AppendReceivedData(stdError, e.Data); process.OutputDataReceived += (_, e) => AppendReceivedData(stdOutput, e.Data); var sw = Stopwatch.StartNew(); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); var taskCompletionSource = new TaskCompletionSource <ProcessResult>(); var cancellationTokenSource = new CancellationTokenSource(timeOutInMilliseconds); cancellationTokenSource.Token.Register(() => { #if NETCOREAPP3_1_OR_GREATER process.Kill(true); #else process.Kill(); #endif var waitForOutputs = Timeout - sw.Elapsed; if (waitForOutputs <= TimeSpan.Zero || waitForOutputs > TimeSpan.FromMinutes(1)) { waitForOutputs = TimeSpan.FromMinutes(1); } outputWaiter.Wait(waitForOutputs); sw.Stop(); taskCompletionSource.TrySetResult(new ProcessResult(process.ExitCode, stdOutput.ToString(), stdError.ToString(), $"{stdOutput}{stdError}", sw.Elapsed)); }, useSynchronizationContext: false); process.Exited += (sender, args) => { var waitForOutputs = Timeout - sw.Elapsed; if (waitForOutputs <= TimeSpan.Zero || waitForOutputs > TimeSpan.FromMinutes(1)) { waitForOutputs = TimeSpan.FromMinutes(1); } outputWaiter.Wait(waitForOutputs); sw.Stop(); taskCompletionSource.TrySetResult(new ProcessResult(process.ExitCode, stdOutput.ToString(), stdError.ToString(), $"{stdOutput}{stdError}", sw.Elapsed)); }; return(await taskCompletionSource.Task); void AppendReceivedData(StringBuilder builder, string?data) { if (data is not null) //null is a sign to the end of the output { builder.AppendLine(data); } else { outputWaiter.Signal(); } } }
public LockInfo(IPEndPoint address, TaskCompletionSource <bool> tcs) { this.Address = address; this.Tcs = tcs; }
public async Task StartRecording() { if (Database.TxMerger.RecordingEnabled) { throw new BadRequestException("Another recording is already in progress"); } using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context)) { var json = await context.ReadForMemoryAsync(RequestBodyStream(), null); var parameters = JsonDeserializationServer.StartTransactionsRecordingOperationParameters(json); var outputFilePath = parameters.File; if (outputFilePath == null) { ThrowRequiredPropertyNameInRequest(nameof(parameters.File)); } if (File.Exists(outputFilePath)) { throw new InvalidOperationException("File " + outputFilePath + " already exists"); } // here path is either a new file -or- an existing directory if (Directory.Exists(outputFilePath)) { throw new InvalidOperationException(outputFilePath + " is a directory. Please enter a path to a file."); } var tcs = new TaskCompletionSource <IOperationResult>(TaskCreationOptions.RunContinuationsAsynchronously); var operationId = ServerStore.Operations.GetNextOperationId(); var command = new StartTransactionsRecordingCommand( Database.TxMerger, parameters.File, () => tcs.SetResult(null) // we don't provide any completion details ); await Database.TxMerger.Enqueue(command); var task = ServerStore.Operations.AddOperation(null, "Recording for: '" + Database.Name + ". Output file: '" + parameters.File + "'", Operations.Operations.OperationType.RecordTransactionCommands, progress => { // push this notification to studio progress(null); return(tcs.Task); }, operationId, new RecordingDetails { DatabaseName = Database.Name, FilePath = parameters.File }); await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream())) { writer.WriteOperationIdAndNodeTag(context, operationId, ServerStore.NodeTag); } } }
public QueueItem(T item, TaskCompletionSource <ProcessedMessageStatus> taskCompletionStatus) { Item = item; TaskCompletionStatus = taskCompletionStatus; }
private async Task ProccessSubscription(TaskCompletionSource <object> successfullyConnected) { try { _proccessingCts.Token.ThrowIfCancellationRequested(); using (var context = new JsonOperationContext(4096, 1024)) { using (var tcpStream = await ConnectToServer().ConfigureAwait(false)) using (var parser = context.ParseMultiFrom(tcpStream)) { _proccessingCts.Token.ThrowIfCancellationRequested(); var readObjectTask = ReadNextObject(parser); var done = await Task.WhenAny(readObjectTask, _disposedTask.Task).ConfigureAwait(false); if (done == _disposedTask.Task) { return; } var connectionStatus = await readObjectTask.ConfigureAwait(false); if (_proccessingCts.IsCancellationRequested) { return; } AssertConnectionState(connectionStatus); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(() => successfullyConnected.TrySetResult(null)); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed readObjectTask = ReadNextObject(parser); if (_proccessingCts.IsCancellationRequested) { return; } var incomingBatch = new List <BlittableJsonReaderObject>(); long lastReceivedEtag = 0; while (_proccessingCts.IsCancellationRequested == false) { BeforeBatch(); bool endOfBatch = false; while (endOfBatch == false && _proccessingCts.IsCancellationRequested == false) { done = await Task.WhenAny(readObjectTask, _disposedTask.Task).ConfigureAwait(false); if (done == _disposedTask.Task) { break; } var receivedMessage = await readObjectTask.ConfigureAwait(false); if (_proccessingCts.IsCancellationRequested) { break; } readObjectTask = ReadNextObject(parser); if (_proccessingCts.IsCancellationRequested) { break; } switch (receivedMessage.Type) { case SubscriptionConnectionServerMessage.MessageType.Data: incomingBatch.Add(receivedMessage.Data); break; case SubscriptionConnectionServerMessage.MessageType.EndOfBatch: endOfBatch = true; break; case SubscriptionConnectionServerMessage.MessageType.Confirm: AfterAcknowledgment(); AfterBatch(incomingBatch.Count); incomingBatch.Clear(); break; case SubscriptionConnectionServerMessage.MessageType.Error: switch (receivedMessage.Status) { case SubscriptionConnectionServerMessage.ConnectionStatus.Closed: throw new SubscriptionClosedException(receivedMessage.Exception ?? string.Empty); default: throw new Exception( $"Connection terminated by server. Exception: {receivedMessage.Exception ?? "None"}"); } default: throw new ArgumentException( $"Unrecognized message '{receivedMessage.Type}' type received from server"); } } foreach (var curDoc in incomingBatch) { NotifySubscribers(curDoc, out lastReceivedEtag); } SendAck(lastReceivedEtag, tcpStream); } } } } catch (OperationCanceledException) { } catch (Exception ex) { if (_proccessingCts.Token.IsCancellationRequested == false) { InformSubscribersOnError(ex); } throw; } }
public void Initialize(TaskCompletionSource <RasConnection> completionSource, Action <StateChangedEventArgs> onStateChangedCallback, Action onCompletedCallback, CancellationToken cancellationToken) { AttachedObject.Initialize(completionSource, onStateChangedCallback, onCompletedCallback, cancellationToken); }
private TaskCompletionSource <bool> CreateState() => _state ?? (_state = new TaskCompletionSource <bool>());
public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { // The full framework implementation doesn't do any argument validation, so // none is done here, either. var tcs = new TaskCompletionSource <WaitForChangedResult>(); FileSystemEventHandler?fseh = null; RenamedEventHandler? reh = null; // Register the event handlers based on what events are desired. The full framework // doesn't register for the Error event, so this doesn't either. if ((changeType & (WatcherChangeTypes.Created | WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed)) != 0) { fseh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, oldName: null, timedOut: false)); } }; if ((changeType & WatcherChangeTypes.Created) != 0) { Created += fseh; } if ((changeType & WatcherChangeTypes.Deleted) != 0) { Deleted += fseh; } if ((changeType & WatcherChangeTypes.Changed) != 0) { Changed += fseh; } } if ((changeType & WatcherChangeTypes.Renamed) != 0) { reh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, timedOut: false)); } }; Renamed += reh; } try { // Enable the FSW if it wasn't already. bool wasEnabled = EnableRaisingEvents; if (!wasEnabled) { EnableRaisingEvents = true; } // Block until an appropriate event arrives or until we timeout. Debug.Assert(EnableRaisingEvents, "Expected EnableRaisingEvents to be true"); tcs.Task.Wait(timeout); // Reset the enabled state to what it was. EnableRaisingEvents = wasEnabled; } finally { // Unregister the event handlers. if (reh != null) { Renamed -= reh; } if (fseh != null) { if ((changeType & WatcherChangeTypes.Changed) != 0) { Changed -= fseh; } if ((changeType & WatcherChangeTypes.Deleted) != 0) { Deleted -= fseh; } if ((changeType & WatcherChangeTypes.Created) != 0) { Created -= fseh; } } } // Return the results. return(tcs.Task.IsCompletedSuccessfully ? tcs.Task.Result : WaitForChangedResult.TimedOutResult); }
public async Task PauseProcessing() { this.queuePausingCompleted = new TaskCompletionSource <bool>(); this.queueStatus = QueueStatus.Paused; await this.queuePausingCompleted.Task; }
public Task ConnectAsync() { var source = new TaskCompletionSource<object>(); _handler.EnqueueMessage(new StartConnectionMessage(source, _endPointDiscoverer)); return source.Task; }
// navigate WebBrowser to the list of urls in a loop static async Task <object> DoWorkAsync(object[] args) { Console.WriteLine("Start working."); var wb = new WebBrowser(); wb.ScriptErrorsSuppressed = true; if (wb.Document == null && wb.ActiveXInstance == null) { throw new ApplicationException("Unable to initialize the underlying WebBrowserActiveX"); } // get the underlying WebBrowser ActiveX object; // this code depends on SHDocVw.dll COM interop assembly, // generate SHDocVw.dll: "tlbimp.exe ieframe.dll", // and add as a reference to the project var wbax = (SHDocVw.WebBrowser)wb.ActiveXInstance; TaskCompletionSource <bool> loadedTcs = null; WebBrowserDocumentCompletedEventHandler documentCompletedHandler = (s, e) => loadedTcs.TrySetResult(true); // turn event into awaitable task TaskCompletionSource <bool> printedTcs = null; SHDocVw.DWebBrowserEvents2_PrintTemplateTeardownEventHandler printTemplateTeardownHandler = (p) => printedTcs.TrySetResult(true); // turn event into awaitable task // navigate to each URL in the list foreach (var url in args) { loadedTcs = new TaskCompletionSource <bool>(); wb.DocumentCompleted += documentCompletedHandler; try { wb.Navigate(url.ToString()); // await for DocumentCompleted await loadedTcs.Task; } finally { wb.DocumentCompleted -= documentCompletedHandler; } // the DOM is ready, Console.WriteLine(url.ToString()); Console.WriteLine(wb.Document.Body.OuterHtml); // print the document printedTcs = new TaskCompletionSource <bool>(); wbax.PrintTemplateTeardown += printTemplateTeardownHandler; try { wb.Print(); // await for PrintTemplateTeardown - the end of printing await printedTcs.Task; } finally { wbax.PrintTemplateTeardown -= printTemplateTeardownHandler; } Console.WriteLine(url.ToString() + " printed."); } wb.Dispose(); Console.WriteLine("End working."); return(null); }
public async Task ConnectionCanSendAndReceiveMessages(TransportType transportType, TransferMode requestedTransferMode) { using (StartLog(out var loggerFactory, testName: $"ConnectionCanSendAndReceiveMessages_{transportType.ToString()}")) { var logger = loggerFactory.CreateLogger <EndToEndTests>(); const string message = "Major Key"; var url = _serverFixture.BaseUrl + "/echo"; var connection = new HttpConnection(new Uri(url), transportType, loggerFactory); connection.Features.Set <ITransferModeFeature>( new TransferModeFeature { TransferMode = requestedTransferMode }); try { var receiveTcs = new TaskCompletionSource <string>(); var closeTcs = new TaskCompletionSource <object>(); connection.OnReceived((data, state) => { logger.LogInformation("Received {length} byte message", data.Length); if (IsBase64Encoded(requestedTransferMode, connection)) { data = Convert.FromBase64String(Encoding.UTF8.GetString(data)); } var tcs = (TaskCompletionSource <string>)state; tcs.TrySetResult(Encoding.UTF8.GetString(data)); return(Task.CompletedTask); }, receiveTcs); connection.Closed += e => { logger.LogInformation("Connection closed"); if (e != null) { receiveTcs.TrySetException(e); closeTcs.TrySetException(e); } else { receiveTcs.TrySetResult(null); closeTcs.TrySetResult(null); } return(Task.CompletedTask); }; logger.LogInformation("Starting connection to {url}", url); await connection.StartAsync().OrTimeout(); logger.LogInformation("Started connection to {url}", url); var bytes = Encoding.UTF8.GetBytes(message); // Need to encode binary payloads sent over text transports if (IsBase64Encoded(requestedTransferMode, connection)) { bytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(bytes)); } logger.LogInformation("Sending {length} byte message", bytes.Length); try { await connection.SendAsync(bytes).OrTimeout(); } catch (OperationCanceledException) { // Because the server and client are run in the same process there is a race where websocket.SendAsync // can send a message but before returning be suspended allowing the server to run the EchoEndpoint and // send a close frame which triggers a cancellation token on the client and cancels the websocket.SendAsync. // Our solution to this is to just catch OperationCanceledException from the sent message if the race happens // because we know the send went through, and its safe to check the response. } logger.LogInformation("Sent message", bytes.Length); logger.LogInformation("Receiving message"); Assert.Equal(message, await receiveTcs.Task.OrTimeout()); logger.LogInformation("Completed receive"); await closeTcs.Task.OrTimeout(); } catch (Exception ex) { logger.LogInformation(ex, "Test threw exception"); throw; } finally { logger.LogInformation("Disposing Connection"); await connection.DisposeAsync().OrTimeout(); logger.LogInformation("Disposed Connection"); } } }
private async void InternalReadAsync(byte[] buffer, int offset, int count, AsyncCallback callback, TaskCompletionSource <int> tcs) { try { int read = await ReadAsync(buffer, offset, count); tcs.TrySetResult(read); } catch (Exception ex) { tcs.TrySetException(ex); } try { callback(tcs.Task); } catch (Exception) { } }
public async Task <byte[]> ExecuteAsync(TimeSpan timeout, string deviceid, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, CancellationToken cancellationToken) { if (methodName == null) { throw new ArgumentNullException(nameof(methodName)); } if (methodName.Contains("/") || methodName.Contains("+") || methodName.Contains("#")) { throw new ArgumentException("The method name cannot contain /, + or #."); } string rpcid = $"{Guid.NewGuid():N}"; var requestTopic = $"{deviceid}/rpc/request/{methodName}"; var responseTopic = $"{deviceid}/rpc/response/{methodName}"; var requestMessage = new MqttApplicationMessageBuilder() .WithTopic(requestTopic) .WithPayload(payload) .WithQualityOfServiceLevel(qualityOfServiceLevel) .Build(); try { var tcs = new TaskCompletionSource <byte[]>(); if (!_waitingCalls.TryAdd(responseTopic, tcs)) { throw new InvalidOperationException(); } await _mqttClient.SubscribeAsync(responseTopic, qualityOfServiceLevel).ConfigureAwait(false); await _mqttClient.PublishAsync(requestMessage).ConfigureAwait(false); using (var timeoutCts = new CancellationTokenSource(timeout)) using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token)) { linkedCts.Token.Register(() => { if (!tcs.Task.IsCompleted && !tcs.Task.IsFaulted && !tcs.Task.IsCanceled) { tcs.TrySetCanceled(); } }); try { var result = await tcs.Task.ConfigureAwait(false); timeoutCts.Cancel(false); return(result); } catch (OperationCanceledException exception) { if (timeoutCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested) { throw new MqttCommunicationTimedOutException(exception); } else { throw; } } } } finally { _waitingCalls.TryRemove(responseTopic, out _); await _mqttClient.UnsubscribeAsync(responseTopic).ConfigureAwait(false); } }
static int GetTaskAndBind(TaskCompletionSource <object> tcs, int js_id) { return(BindExistingObject(tcs.Task, js_id)); }
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var message = this.messageFactory.CreateMessage(request, options); SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments); }
private async void SpeechRecognitionFromFile_ButtonClicked() { stopRecognitionTaskCompletionSource = new TaskCompletionSource <int>(); if (!AreKeysValid()) { NotifyUser("Subscription Key is missing!", NotifyType.ErrorMessage); return; } else { NotifyUser(" ", NotifyType.StatusMessage); } // User can also specify files under the ApplicationData.LocalFolder or Package.InstalledLocation string filename = "ms-appx:///Assets/whatstheweatherlike.wav"; StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(filename)); if (file != null) { // Creates an instance of a speech config with specified and service region (e.g., "westus"). var config = SpeechConfig.FromSubscription(this.SubscriptionKey, this.Region); config.SpeechRecognitionLanguage = this.RecognitionLanguage; // Creates a speech recognizer using file as audio input. using (var audioInput = AudioConfig.FromWavFileInput(file.Path)) { using (var recognizer = new SpeechRecognizer(config, audioInput)) { // Subscribes to events. recognizer.Recognizing += (s, e) => { NotifyUser(e.Result.Text, NotifyType.StatusMessage); }; recognizer.Recognized += (s, e) => { string str = ""; if (e.Result.Reason == ResultReason.RecognizedSpeech) { str = $"RECOGNIZED: Text={e.Result.Text}"; } else if (e.Result.Reason == ResultReason.NoMatch) { str = $"NOMATCH: Speech could not be recognized."; } NotifyUser(str, NotifyType.StatusMessage); }; recognizer.Canceled += (s, e) => { StringBuilder sb = new StringBuilder(); sb.AppendLine($"CANCELED: Reason={e.Reason}"); if (e.Reason == CancellationReason.Error) { sb.AppendLine($"CANCELED: ErrorDetails={e.ErrorDetails}"); sb.AppendLine($"CANCELED: Did you update the subscription info?"); } NotifyUser(sb.ToString(), NotifyType.StatusMessage); }; recognizer.SessionStarted += (s, e) => { NotifyUser("Session started event.", NotifyType.StatusMessage); }; recognizer.SessionStopped += (s, e) => { NotifyUser("Session stopped event.", NotifyType.StatusMessage); NotifyUser("Stop recognition.", NotifyType.StatusMessage); stopRecognitionTaskCompletionSource.TrySetResult(0); }; // Starts continuous recognition. Uses StopContinuousRecognitionAsync() to stop recognition. await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false); // Waits for completion. await stopRecognitionTaskCompletionSource.Task.ConfigureAwait(false); // Stops recognition. await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false); } } } else { NotifyUser($"Can't open {filename} !", NotifyType.ErrorMessage); } }
// Test error if not reached within a timeout public static Task <TResult> AwaitWithTimeout <TResult>(this TaskCompletionSource <TResult> taskSource) { return(taskSource.Task); }
private void UpdateBucket(BaseRestRequest request, RestResponse response, TaskCompletionSource <bool> ratelimitTcs) { var bucket = request.RateLimitBucket; if (response.Headers == null) { if (response.ResponseCode != 429) // do not fail when ratelimit was or the next request will be scheduled hitting the rate limit again { this.FailInitialRateLimitTest(request, ratelimitTcs); } return; } var hs = response.Headers; if (hs.TryGetValue("X-RateLimit-Global", out var isglobal) && isglobal.ToLowerInvariant() == "true") { if (response.ResponseCode != 429) { this.FailInitialRateLimitTest(request, ratelimitTcs); } return; } var r1 = hs.TryGetValue("X-RateLimit-Limit", out var usesmax); var r2 = hs.TryGetValue("X-RateLimit-Remaining", out var usesleft); var r3 = hs.TryGetValue("X-RateLimit-Reset", out var reset); var r4 = hs.TryGetValue("X-Ratelimit-Reset-After", out var resetAfter); var r5 = hs.TryGetValue("X-Ratelimit-Bucket", out var hash); if (!r1 || !r2 || !r3 || !r4) { //If the limits were determined before this request, make the bucket initial again. if (response.ResponseCode != 429) { this.FailInitialRateLimitTest(request, ratelimitTcs, ratelimitTcs == null); } return; } var clienttime = DateTimeOffset.UtcNow; var resettime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(double.Parse(reset, CultureInfo.InvariantCulture)); var servertime = clienttime; if (hs.TryGetValue("Date", out var raw_date)) { servertime = DateTimeOffset.Parse(raw_date, CultureInfo.InvariantCulture).ToUniversalTime(); } var resetdelta = resettime - servertime; //var difference = clienttime - servertime; //if (Math.Abs(difference.TotalSeconds) >= 1) //// request.Discord.Logger.LogMessage(LogLevel.DebugBaseDiscordClient.RestEventId, $"Difference between machine and server time: {difference.TotalMilliseconds.ToString("#,##0.00", CultureInfo.InvariantCulture)}ms", DateTime.Now); //else // difference = TimeSpan.Zero; if (request.RateLimitWaitOverride.HasValue) { resetdelta = TimeSpan.FromSeconds(request.RateLimitWaitOverride.Value); } var newReset = clienttime + resetdelta; if (this.UseResetAfter) { bucket.ResetAfter = TimeSpan.FromSeconds(double.Parse(resetAfter, CultureInfo.InvariantCulture)); newReset = clienttime + bucket.ResetAfter.Value + (request.RateLimitWaitOverride.HasValue ? resetdelta : TimeSpan.Zero); bucket._resetAfterOffset = newReset; } else { bucket.Reset = newReset; } var maximum = int.Parse(usesmax, CultureInfo.InvariantCulture); var remaining = int.Parse(usesleft, CultureInfo.InvariantCulture); if (ratelimitTcs != null) { // initial population of the ratelimit data bucket.SetInitialValues(maximum, remaining, newReset); _ = Task.Run(() => ratelimitTcs.TrySetResult(true)); } else { // only update the bucket values if this request was for a newer interval than the one // currently in the bucket, to avoid issues with concurrent requests in one bucket // remaining is reset by TryResetLimit and not the response, just allow that to happen when it is time if (bucket._nextReset == 0) { bucket._nextReset = newReset.UtcTicks; } } this.UpdateHashCaches(request, bucket, hash); }
private async void SpeechRecognitionFromStream_ButtonClicked(object sender, RoutedEventArgs e) { stopRecognitionTaskCompletionSource = new TaskCompletionSource <int>(); AudioConfig audioInput = null; BinaryReader reader = null; Stream stream = null; if (!AreKeysValid()) { NotifyUser("Subscription Key is missing!", NotifyType.ErrorMessage); return; } else { NotifyUser(" ", NotifyType.StatusMessage); } var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.FileTypeFilter.Add(".wav"); StorageFile file = await picker.PickSingleFileAsync(); if (file == null) { string s = string.Format(CultureInfo.InvariantCulture, "Can't open {0} !", file.Path); NotifyUser(s, NotifyType.ErrorMessage); return; } try { stream = (await file.OpenReadAsync()).AsStreamForRead(); reader = new BinaryReader(stream); // Create an audio stream from a wav file. audioInput = MicrosoftSpeechSDKSamples.Helper.OpenWavFile(reader); // Creates an instance of a speech config with specified and service region (e.g., "westus"). var config = SpeechConfig.FromSubscription(this.SubscriptionKey, this.Region); config.SpeechRecognitionLanguage = this.RecognitionLanguage; // Creates a speech recognizer using file as audio input. using (var recognizer = new SpeechRecognizer(config, audioInput)) { // Subscribes to events. recognizer.Recognizing += (s, ee) => { NotifyUser(ee.Result.Text, NotifyType.StatusMessage); }; recognizer.Recognized += (s, ee) => { string str = ""; if (ee.Result.Reason == ResultReason.RecognizedSpeech) { str = $"RECOGNIZED: Text={ee.Result.Text}"; } else if (ee.Result.Reason == ResultReason.NoMatch) { str = $"NOMATCH: Speech could not be recognized."; } NotifyUser(str, NotifyType.StatusMessage); }; recognizer.Canceled += (s, ee) => { StringBuilder sb = new StringBuilder(); sb.AppendLine($"CANCELED: Reason={ee.Reason}"); if (ee.Reason == CancellationReason.Error) { sb.AppendLine($"CANCELED: ErrorDetails={ee.ErrorDetails}"); sb.AppendLine($"CANCELED: Did you update the subscription info?"); } NotifyUser(sb.ToString(), NotifyType.StatusMessage); }; recognizer.SessionStarted += (s, ee) => { NotifyUser("Session started event.", NotifyType.StatusMessage); }; recognizer.SessionStopped += (s, ee) => { NotifyUser("Session stopped event.", NotifyType.StatusMessage); NotifyUser("Stop recognition.", NotifyType.StatusMessage); stopRecognitionTaskCompletionSource.TrySetResult(0); }; // Starts continuous recognition. Uses StopContinuousRecognitionAsync() to stop recognition. await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false); // Waits for completion. await stopRecognitionTaskCompletionSource.Task.ConfigureAwait(false); // Stops recognition. await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false); } } catch (System.FormatException ex) { NotifyUser(ex.ToString(), NotifyType.ErrorMessage); } finally { if (reader != null) { reader.Dispose(); } if (audioInput != null) { audioInput.Dispose(); } if (stream != null) { stream.Dispose(); } } }
static void SetTaskSourceFailure(TaskCompletionSource <object> tcs, string reason) { tcs.SetException(new JSException(reason)); }
public abstract Task <T> WaitForResponse(uint ResponseID, TaskCompletionSource <T> tcs);
static void SetTaskSourceResult(TaskCompletionSource <object> tcs, object result) { tcs.SetResult(result); }
// to allow proper rescheduling of the first request from a bucket private async Task ExecuteRequestAsync(BaseRestRequest request, RateLimitBucket bucket, TaskCompletionSource <bool> ratelimitTcs) { if (this._disposed) { return; } try { await this.GlobalRateLimitEvent.WaitAsync(); if (bucket == null) { bucket = request.RateLimitBucket; } if (ratelimitTcs == null) { ratelimitTcs = await this.WaitForInitialRateLimit(bucket); } if (ratelimitTcs == null) // ckeck rate limit only if we are not the probe request { var now = DateTimeOffset.UtcNow; await bucket.TryResetLimitAsync(now); // Decrement the remaining number of requests as there can be other concurrent requests before this one finishes and has a chance to update the bucket #pragma warning disable 420 // interlocked access is always volatile if (Interlocked.Decrement(ref bucket._remaining) < 0) #pragma warning restore 420 // blaze it { request.Discord?.Logger.LogDebug(LoggerEvents.RatelimitDiag, "Request for {0} is blocked", bucket.ToString()); var delay = bucket.Reset - now; var resetDate = bucket.Reset; if (this.UseResetAfter) { delay = bucket.ResetAfter.Value; resetDate = bucket._resetAfterOffset; } if (delay < new TimeSpan(-TimeSpan.TicksPerMinute)) { request.Discord?.Logger.LogError(LoggerEvents.RatelimitDiag, "Failed to retrieve ratelimits - giving up and allowing next request for bucket"); bucket._remaining = 1; } if (delay < TimeSpan.Zero) { delay = TimeSpan.FromMilliseconds(100); } request.Discord?.Logger.LogWarning(LoggerEvents.RatelimitPreemptive, "Pre-emptive ratelimit triggered - waiting until {0:yyyy-MM-dd HH:mm:ss zzz} ({1:c}).", resetDate, delay); Task.Delay(delay) .ContinueWith(_ => this.ExecuteRequestAsync(request, null, null)) .LogTaskFault(request.Discord?.Logger, LogLevel.Error, LoggerEvents.RestError, "Error while executing request"); return; } request.Discord?.Logger.LogDebug(LoggerEvents.RatelimitDiag, "Request for {0} is allowed", bucket.ToString()); } else { request.Discord?.Logger.LogDebug(LoggerEvents.RatelimitDiag, "Initial request for {0} is allowed", bucket.ToString()); } var req = this.BuildRequest(request); var response = new RestResponse(); try { if (this._disposed) { return; } var res = await HttpClient.SendAsync(req, CancellationToken.None).ConfigureAwait(false); var bts = await res.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var txt = Utilities.UTF8.GetString(bts, 0, bts.Length); request.Discord?.Logger.LogTrace(LoggerEvents.RestRx, txt); response.Headers = res.Headers.ToDictionary(xh => xh.Key, xh => string.Join("\n", xh.Value), StringComparer.OrdinalIgnoreCase); response.Response = txt; response.ResponseCode = (int)res.StatusCode; } catch (HttpRequestException httpex) { request.Discord?.Logger.LogError(LoggerEvents.RestError, httpex, "Request to {0} triggered an HttpException", request.Url); request.SetFaulted(httpex); this.FailInitialRateLimitTest(request, ratelimitTcs); return; } this.UpdateBucket(request, response, ratelimitTcs); Exception ex = null; switch (response.ResponseCode) { case 400: case 405: ex = new BadRequestException(request, response); break; case 401: case 403: ex = new UnauthorizedException(request, response); break; case 404: ex = new NotFoundException(request, response); break; case 413: ex = new RequestSizeException(request, response); break; case 429: ex = new RateLimitException(request, response); // check the limit info and requeue this.Handle429(response, out var wait, out var global); if (wait != null) { if (global) { request.Discord?.Logger.LogError(LoggerEvents.RatelimitHit, "Global ratelimit hit, cooling down"); try { this.GlobalRateLimitEvent.Reset(); await wait.ConfigureAwait(false); } finally { // we don't want to wait here until all the blocked requests have been run, additionally Set can never throw an exception that could be suppressed here _ = this.GlobalRateLimitEvent.SetAsync(); } this.ExecuteRequestAsync(request, bucket, ratelimitTcs) .LogTaskFault(request.Discord?.Logger, LogLevel.Error, LoggerEvents.RestError, "Error while retrying request"); } else { request.Discord?.Logger.LogError(LoggerEvents.RatelimitHit, "Ratelimit hit, requeueing request to {0}", request.Url); await wait.ConfigureAwait(false); this.ExecuteRequestAsync(request, bucket, ratelimitTcs) .LogTaskFault(request.Discord?.Logger, LogLevel.Error, LoggerEvents.RestError, "Error while retrying request"); } return; } break; case 500: ex = new ServerErrorException(request, response); break; } if (ex != null) { request.SetFaulted(ex); } else { request.SetCompleted(response); } } catch (Exception ex) { request.Discord?.Logger.LogError(LoggerEvents.RestError, ex, "Request to {0} triggered an exception", request.Url); // if something went wrong and we couldn't get rate limits for the first request here, allow the next request to run if (bucket != null && ratelimitTcs != null && bucket._limitTesting != 0) { this.FailInitialRateLimitTest(request, ratelimitTcs); } if (!request.TrySetFaulted(ex)) { throw; } } finally { // Get and decrement active requests in this bucket by 1. _ = this.RequestQueue.TryGetValue(bucket.BucketId, out var count); this.RequestQueue[bucket.BucketId] = Interlocked.Decrement(ref count); // If it's 0 or less, we can remove the bucket from the active request queue, // along with any of its past routes. if (count <= 0) { foreach (var r in bucket.RouteHashes) { if (this.RequestQueue.ContainsKey(r)) { _ = this.RequestQueue.TryRemove(r, out _); } } } } }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { var tcs = new TaskCompletionSource<object>(); context.ApplicationInstance.CompleteRequest(); var clientId = new Guid(context.Request["clientId"]); var jsons = new List<CommandMessage>(); var bus = SheepJaxComet.PollingCommandBus; var obs = bus.GetObservable(clientId).Replay(); var subscription = obs.Connect(); obs.TakeUntil(Observable.Interval(LongPollTimeout)) .TakeUntil(obs.Take(1).Delay(BatchInterval)) .Subscribe(jsons.Add, context.AddError, ()=> { try { subscription.Dispose(); context.Response.Write("[" + string.Join(",", jsons.Select(x => x.Message)) + "]"); bus.Consumed(jsons.LastOrDefault()); } catch (Exception ex) { _logger.Error("SheepJax exception thrown while writing to long-polling connection", ex); } finally { tcs.SetResult(null); cb(tcs.Task); } }); return tcs.Task; }