/// <summary> /// This is the main entry point for your service replica. /// This method executes when this replica of your service becomes primary and has write status. /// </summary> /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param> protected override async Task RunAsync(CancellationToken cancellationToken) { try { _freeHandlers = Enumerable.Range(1, HandlerCount).ToConcurrentQueue(); await SetupServiceBus(); while (!cancellationToken.IsCancellationRequested) { try { //if (_messageReceiver.IsClosedOrClosing) //{ // _bigBrother.Publish(new MessageReceiverClosingEvent { FabricId = $"{this.Context.ServiceName}:{this.Context.ReplicaId}" }); // continue; //} var(messages, activeReaderId) = await ReceiveMessagesFromActiveReceiver(); await ServiceReceiversLifecycle(); if (messages == null || messages.Count == 0) { // ReSharper disable once MethodSupportsCancellation - no need to cancellation token here #if DEBUG //this is done due to enable SF mocks to run as receiver call is not awaited and therefore RunAsync would never await await Task.Delay(TimeSpan.FromMilliseconds(10)); #endif continue; } foreach (var message in messages) { var messageData = new MessageData(Encoding.UTF8.GetString(message.Body), _initData.EventType, _initData.SubscriberName, Context.ServiceName.ToString(), _initData.DlqMode != null); var handlerId = GetFreeHandlerId(); messageData.HandlerId = handlerId; messageData.CorrelationId = Guid.NewGuid().ToString(); var handleData = new MessageDataHandle { LockToken = _serviceBusManager.GetLockToken(message), ReceiverId = activeReaderId }; _inflightMessages.TryAdd(messageData.CorrelationId, handleData); //should again always succeed await _proxyFactory.CreateActorProxy <IEventHandlerActor>( new ActorId(messageData.EventHandlerActorId), serviceName : ServiceNaming.EventHandlerServiceShortName) .Handle(messageData); } } catch (ServiceBusCommunicationException sbCommunicationException) { BigBrother.Write(sbCommunicationException.ToExceptionEvent()); await SetupServiceBus(); } catch (Exception e) { BigBrother.Write(e.ToExceptionEvent()); } } _bigBrother.Publish(new Common.Telemetry.CancellationRequestedEvent { FabricId = $"{Context.ServiceName}:{Context.ReplicaId}" }); } catch (Exception e) { BigBrother.Write(e.ToExceptionEvent()); } }