public async Task Should_execute_in_correct_order() { //arrange var semaphore = new SemaphoreQueue(1); var numbers = new int[5000]; var tasks = new List <Task>(); //act for (var i = 0; i < 5000; i++) { var intCopy = i; tasks.Add(semaphore.WaitAsync(CancellationToken.None).ContinueWith(task => { semaphore.Release(); return(numbers[intCopy] = intCopy); })); } await Task.WhenAll(tasks); //assert for (var i = 0; i < 5000; i++) { numbers[i].Should().Be(i); } }
private async Task HandleInputChange(string oldValue, string newValue) { await _semaphoreQueue.WaitAsync(); await Task.Run(async() => { if (oldValue.Length < newValue.Length) { var addedSubstring = newValue.Substring(oldValue.Length); addedSubstring = addedSubstring.ToUpper(); foreach (var c in addedSubstring) { var x = c; if (char.IsLetter(c)) { x = await Enigma.Encrypt(c); } Output += x; } } else if (oldValue.Length > newValue.Length) { Output = Output.Remove(newValue.Length); } }); _semaphoreQueue.Release(); }
async Task OnDisconnectedFromService(DisconnectedFromServerEvent arg) { await _semaphoreQueue.WaitAsync(); try { await ClearDevicesCollection(); } catch (Exception ex) { _log.WriteLine(ex); } finally { _semaphoreQueue.Release(); } }
public async Task <IActionResult> Post() { var ms = new MemoryStream(); await Request.Body.CopyToAsync(ms); ms.Seek(0, SeekOrigin.Begin); try { await commandSemaphore.WaitAsync(); _logger.LogInformation($"{DateTime.Now}: Received request, attempting to parse it as LaTeX file..."); var result = await GetTextFromLaTeX(ms); if (result != null) { _logger.LogInformation($"{DateTime.Now}: LaTeX parse successful. Result length = {result.Length}"); return(Content(result, "text/plain", Encoding.UTF8)); } _logger.LogInformation($"{DateTime.Now}: attempting to parse it as zipped LaTeX group file containing 'main.tex'..."); result = await GetTextFromLaTeXZip(ms); if (result != null) { _logger.LogInformation($"{DateTime.Now}: LaTeX zip group parse successful. Result length = {result.Length}"); return(Content(result, "text/plain", Encoding.UTF8)); } //result = await GetTextFromDocxUsingCustomLibrary(ms); //if (result != null) // return Content(result); //result = await GetTextFromDoc(ms); //if (result != null) // return Content(result); _logger.LogInformation($"{DateTime.Now}: attempting to parse it as a word document..."); result = await GetTextFromDocDocxUsingLibreOffice(ms); if (result != null) { _logger.LogInformation($"{DateTime.Now}: LibreOffice parse successful. Result length = {result.Length}"); return(Content(result, "text/plain", Encoding.UTF8)); } _logger.LogInformation($"{DateTime.Now}: Failed to parse the input file. Will respond with 415."); return(StatusCode(415)); } finally { commandSemaphore.Release(); } }
public async Task ProcessAsync <T>(IMessageStateHandler <T> messageStateHandler, IMessageProcessor next, CancellationToken cancellationToken) where T : class, IMessage { try { await _semaphoreQueue.WaitAsync().ConfigureAwait(false); await next.ProcessAsync(messageStateHandler, cancellationToken).ConfigureAwait(false); } finally { _semaphoreQueue.Release(); } }
public async Task Should_wait() { //arrange var semaphore = new SemaphoreQueue(1); var countable = new Mock <ICountable>(); //act #pragma warning disable 4014 semaphore.WaitAsync(CancellationToken.None).ContinueWith(task => countable.Object.Count()); semaphore.WaitAsync(CancellationToken.None).ContinueWith(task => countable.Object.Count()); semaphore.WaitAsync(CancellationToken.None).ContinueWith(task => countable.Object.Count()); #pragma warning restore 4014 await Task.Delay(500); //assert countable.Verify(x => x.Count(), Times.Once); semaphore.Release(); }
public async Task <T> GetItem(string key) { try { await semaphore.WaitAsync(); if (!data.ContainsKey(key)) { data[key] = await RetrieveItem(key); } return(data[key]); } finally { semaphore.Release(); } }
private async Task <bool> PumpAsync(CancellationToken cancellationToken) { try { var prefetchCount = _settings.PrefetchCount > 0 ? _settings.PrefetchCount : 1; var messages = await _queueClient.GetMessagesAsync(prefetchCount).ConfigureAwait(false); if (messages.Length == 0) { return(false); } foreach (var redisMessage in messages) { if (redisMessage != null) { await _maxConcurrent.WaitAsync(cancellationToken).ConfigureAwait(false); var timeoutToken = new CancellationTokenSource(_settings.MessageLockTimeout); var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken.Token); #pragma warning disable 4014 Task.Run(async() => await ProcessMessageAsync(redisMessage, linkedToken.Token).ConfigureAwait(false), timeoutToken.Token) .ContinueWith(task2 => { _maxConcurrent.Release(); timeoutToken.Dispose(); linkedToken.Dispose(); }).ConfigureAwait(false); #pragma warning restore 4014 } else { return(false); } } return(true); } catch (Exception e) { _hostConfiguration.Log.Error(e, "Redis message pump error"); return(false); } }
public async Task ProcessAsync <T>(IMessageStateHandler <T> messageStateHandler, IPipelineInformation pipelineInformation, IMessageProcessor next, CancellationToken cancellationToken) where T : class, IMessage { var queueName = AutoMessageMapper.GetQueueName <T>(); var log = pipelineInformation?.HostConfiguration?.Log; log?.Debug("{ThreadCount} remaining threads that can process messages in {QueueName} in {Name}", _semaphoreQueue.CurrentCount, queueName, nameof(ThrottlingMiddleware)); await _semaphoreQueue.WaitAsync(cancellationToken).ConfigureAwait(false); try { await next.ProcessAsync(messageStateHandler, cancellationToken).ConfigureAwait(false); } finally { _semaphoreQueue.Release(); } }
/// <summary> /// Send message without blocking current thread using IMessenger /// </summary> /// <param name="message">Message to send using IMessenger</param> void SendMessage <T>(T message) { Task.Run(async() => { await _sendMessageSemaphore.WaitAsync(); try { _messenger.Send(message); } catch (Exception ex) { _log.WriteLine(ex); } finally { _sendMessageSemaphore.Release(); } }); }
private async Task <bool> PumpAsync() { try { var prefetchCount = _settings.PrefetchCount > 0 ? _settings.PrefetchCount : 1; foreach (var redisMessage in await GetMessagesAsync(prefetchCount).ConfigureAwait(false)) { if (redisMessage != null) { await _maxConcurrent.WaitAsync(CancellationToken.None).ConfigureAwait(false); var cts = new CancellationTokenSource(_settings.MessageLockTimeout); #pragma warning disable 4014 ProcessMessageAsync(redisMessage, cts.Token).ContinueWith(task2 => _maxConcurrent.Release()); #pragma warning restore 4014 } else { return(false); } } return(true); } catch (Exception e) { _hostConfiguration.Log.Error(e, "Redis message pump error"); return(false); } }