CQRSMicroservices.ServiceFabric.QueryModelBuilderService.QueryModelBuilderService.RunAsync C# (CSharp) Method

RunAsync() protected method

This is the main entry point for your service's partition replica. RunAsync executes when the primary replica for this partition has write status.
protected RunAsync ( CancellationToken cancellationToken ) : Task
cancellationToken System.Threading.CancellationToken Canceled when Service Fabric terminates this partition's replica.
return Task
    protected override async Task RunAsync(CancellationToken cancellationToken)
    {
      var queryModelBuilder = GetQueryModelBuilder();
      var queue = await StateManager.GetOrAddAsync<IReliableQueue<string>>("queryModelBuilderQueue");

      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 queryModelBuilder.Handle(CqrsApplication.GetService<IDeserializer>().CreateEvent(JObject.Parse(message)));

            await tx.CommitAsync();
          }
        }

        await _semaphore.WaitAsync(cancellationToken);
      }
    }