/// <summary> /// This is the main entry point for your service's partition replica. /// RunAsync executes when the primary replica for this partition has write status. /// </summary> /// <param name="cancellationToken">Canceled when Service Fabric terminates this partition's replica.</param> protected override async Task RunAsync(CancellationToken cancellationToken) { var queue = await StateManager.GetOrAddAsync<IReliableQueue<string>>("eventBusQueue"); // We use the ServiceFabricEventBus as our way of dispatching in this service. // The class has all the registered builders and can locate them through the ServiceClient. var eventBus = new ServiceFabricEventBus(); Handlers.QueryModelBuilders.ToList().ForEach(eventBus.RegisterBuilder); var deserializer = new Deserializer(); var count = (int)await queue.GetCountAsync(); if(count > 0) { _semaphore.Release(count); } while(true) { cancellationToken.ThrowIfCancellationRequested(); using(ITransaction tx = StateManager.CreateTransaction()) { ConditionalResult<string> dequeueReply = await queue.TryDequeueAsync(tx); if(dequeueReply.HasValue) { string message = dequeueReply.Value; await eventBus.Dispatch(deserializer.CreateEvent(JObject.Parse(message))); await tx.CommitAsync(); } } await _semaphore.WaitAsync(cancellationToken); } }