public async Task RegisterEndpoint(IEndPoint endPoint) { ASSERT((endPoint != null) && (!string.IsNullOrWhiteSpace(endPoint.ID)), $"Missing or invalid parameter '{nameof(endPoint)}'"); Action checkExisting = () => { var existing = RegisteredEndpoints.TryGet(endPoint.ID); // nb: read-only => no need for "lock{}" if (existing == null) { // OK return; } // Not OK throw new EndpointAlreadyRegistered($"The endpoint '{endPoint.ID}' has already been registered", existing); }; checkExisting(); if (endPoint.IsOneShot) { // Check pending messages var messages = await RestoreMessages(endPoint.ID); if (messages != null) { ASSERT(messages.Count > 0, $"'{nameof(messages)}' is not supposed to be empty here"); await endPoint.ReceiveMessages(messages); // nb: one-shot -> No need to register this endpoint ... } else // There's no pending messages { // Register endpoint lock ( Locker ) { checkExisting(); RegisteredEndpoints.Add(endPoint.ID, endPoint); } // Re-check pending messages (in case they've been added in the mean-time ...) await CheckPendingMessages(endPoint.ID); } } else // not endPoint.IsOneShot { // Register endpoint lock ( Locker ) { checkExisting(); RegisteredEndpoints.Add(endPoint.ID, endPoint); } // Re-check pending messages (in case they've been added in the mean-time ...) await CheckPendingMessages(endPoint.ID); } }
public Task RegisterEndpoint(IEndPoint endPoint) { ASSERT((endPoint != null) && (!string.IsNullOrWhiteSpace(endPoint.ID)), $"Missing or invalid parameter '{nameof(endPoint)}'"); var id = endPoint.ID; MessagesQueueItem queue; lock ( Locker ) { // Check if an existing one is already registered { var existing = EndPoints.TryGet(id); if (existing != null) { throw new BrokerBase.EndpointAlreadyRegistered($"The endpoint '{id}' has already been registered", existing); } } // Are there any messages in the queue ? queue = MessagesQueues.TryGet(id); if (queue != null) { MessagesQueues.Remove(id); if (endPoint.IsOneShot && (queue.Messages.Count > 0)) { // 'ReceiveMessages()' would be invoked immediately => This endpoint does not need to be registered (i.e. would have to unregister it immediately after ...) goto BREAK; } } // Register endpoint EndPoints.Add(id, endPoint); BREAK :; } if (queue != null) { // There were messages in the queue => Send them var notAwaited = Task.Run(async() => // nb: Run asynchroneously { try { await endPoint.ReceiveMessages(queue.Messages); } catch (System.Exception ex) { FAIL($"endPoint.ReceiveMessages() threw an exception ({ex.GetType().FullName}): {ex.Message}"); } }); } return(Task.FromResult(0)); }