private async Task BackgroundDispatchUsingSync(int amountToClear, int minimumAge) { if (await _backgroundClearSemaphoreToken.WaitAsync(TimeSpan.Zero)) { await _clearSemaphoreToken.WaitAsync(CancellationToken.None); try { var messages = OutBox.OutstandingMessages(minimumAge, amountToClear); s_logger.LogInformation("Found {NumberOfMessages} to clear out of amount {AmountToClear}", messages.Count(), amountToClear); Dispatch(messages); s_logger.LogInformation("Messages have been cleared"); } catch (Exception e) { s_logger.LogError(e, "Error while dispatching from outbox"); } finally { _clearSemaphoreToken.Release(); _backgroundClearSemaphoreToken.Release(); } CheckOutstandingMessages(); } else { s_logger.LogInformation("Skipping dispatch of messages as another thread is running"); } }
private void OutstandingMessagesCheck() { if (Monitor.TryEnter(_checkOutStandingMessagesObject)) { s_logger.LogDebug("Begin count of outstanding messages"); try { if (OutBox != null) { _outStandingCount = OutBox .OutstandingMessages(ProducerRegistry.GetDefaultProducer() .MaxOutStandingCheckIntervalMilliSeconds) .Count(); return; } // else if(AsyncOutbox != null) // { // //TODO: There is no async version of this call at present; the thread here means that won't hurt if implemented // _outStandingCount = AsyncOutbox // .OutstandingMessages(ProducerRegistry.GetDefaultProducer().MaxOutStandingCheckIntervalMilliSeconds) // .Count(); // return; // } _outStandingCount = 0; } catch (Exception ex) { //if we can't talk to the outbox, we would swallow the exception on this thread //by setting the _outstandingCount to -1, we force an exception s_logger.LogError(ex, "Error getting outstanding message count, reset count"); _outStandingCount = 0; } finally { s_logger.LogDebug("Current outstanding count is {OutStandingCount}", _outStandingCount); Monitor.Exit(_checkOutStandingMessagesObject); } } }