public void Start(CancellationToken cancellationToken) { Task.Factory.StartNew( () => { try { foreach (var key in _enqueuedKeys.GetConsumingEnumerable(cancellationToken)) { if (!cancellationToken.IsCancellationRequested) { ProcessPartition(key); } else { EnqueueIfNotExists(key); return; } } } catch (OperationCanceledException) { return; } }, TaskCreationOptions.LongRunning); // Query through all partitions to check for pending events, as there could be // stored events that were never published before the system was rebooted. Task.Factory.StartNew( () => { foreach (var partitionKey in _queue.GetSourceIdsWithPendingEvents()) { if (cancellationToken.IsCancellationRequested) { return; } EnqueueIfNotExists(partitionKey); } }, TaskCreationOptions.LongRunning); }