private void Run() { if (PendingTaskCount < MaxTaskCount && QueueMessager.HasValue()) { var message = (dynamic)QueueMessager.Dequeue(); IncreasePendingTaskCount(); Task.Run(() => { if (message.Status != MessgaeStatus.Pending) { MessageManager.AddPendingMessgae(message.Pending()); } HandlerManager.Handle(message, CancellationToken.None); MessageManager.AddHistoryMessgae(message.Completed()); DecreasePendingTaskCount(); }) .ContinueWith((t) => { _logger.Write(t?.Exception?.ToTetailMessage()); MessageManager.AddErrorMessgae(message.Error()); DecreasePendingTaskCount(); }, TaskContinuationOptions.OnlyOnFaulted); } else if (PendingTaskCount == 0 && !QueueMessager.HasValue()) { Task.Delay(DelayTimeWhenNoMessageCome).GetAwaiter().GetResult(); } else { Task.Delay(TimeSpan.FromMilliseconds(1)).GetAwaiter().GetResult(); } }