当前位置: 首页>>代码示例>>C#>>正文


C# BrokeredMessage.AbandonAsync方法代码示例

本文整理汇总了C#中BrokeredMessage.AbandonAsync方法的典型用法代码示例。如果您正苦于以下问题:C# BrokeredMessage.AbandonAsync方法的具体用法?C# BrokeredMessage.AbandonAsync怎么用?C# BrokeredMessage.AbandonAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BrokeredMessage的用法示例。


在下文中一共展示了BrokeredMessage.AbandonAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CompleteProcessingMessageAsync

 /// <summary>
 /// This method completes processing of the specified message, after the job function has been invoked.
 /// </summary>
 /// <param name="message">The message to complete processing for.</param>
 /// <param name="result">The <see cref="FunctionResult"/> from the job invocation.</param>
 /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use</param>
 /// <returns></returns>
 public virtual async Task CompleteProcessingMessageAsync(BrokeredMessage message, FunctionResult result, CancellationToken cancellationToken)
 {
     if (!result.Succeeded)
     {
         cancellationToken.ThrowIfCancellationRequested();
         await message.AbandonAsync();
     }
 }
开发者ID:GPetrites,项目名称:azure-webjobs-sdk,代码行数:15,代码来源:MessageProcessor.cs

示例2: HandleDispatchCompletion

        private async Task HandleDispatchCompletion(Task t, BrokeredMessage m)
        {
            if (t.IsFaulted)
            {
                var exception = t.Exception;
                Logger.Error(exception, "Message dispatch failed");
                await m.AbandonAsync(ExceptionDetailsAsProperties(exception));
                return;
            }

            Logger.Debug("Dispatched message: {0} from {1}", m, m.ReplyTo);
            await m.CompleteAsync();
        }
开发者ID:nhuhuynh,项目名称:Nimbus,代码行数:13,代码来源:MessagePump.cs

示例3: WaitAndAbandonMessage

        async Task IMessageSessionAsyncHandler.OnMessageAsync(MessageSession session, BrokeredMessage message)
        {
            if (_receiver.IsShuttingDown)
            {
                await WaitAndAbandonMessage(message).ConfigureAwait(false);
                return;
            }

            using (var delivery = _tracker.BeginDelivery())
            {
                if (_log.IsDebugEnabled)
                    _log.DebugFormat("Receiving {0}:{1}({3}) - {2}", delivery.Id, message.MessageId, _receiver.QueuePath, session.SessionId);

                var context = new ServiceBusReceiveContext(_receiver.InputAddress, message, _context, _sendEndpointProvider, _publishEndpointProvider);

                context.GetOrAddPayload<MessageSessionContext>(() => new BrokeredMessageSessionContext(session));
                context.GetOrAddPayload(() => _context);

                try
                {
                    await _context.PreReceive(context).ConfigureAwait(false);

                    await _receiver.ReceivePipe.Send(context).ConfigureAwait(false);

                    await context.CompleteTask.ConfigureAwait(false);

                    await message.CompleteAsync().ConfigureAwait(false);

                    await _context.PostReceive(context).ConfigureAwait(false);

                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Receive completed: {0}", message.MessageId);
                }
                catch (Exception ex)
                {
                    if (_log.IsErrorEnabled)
                        _log.Error($"Received faulted: {message.MessageId}", ex);

                    await message.AbandonAsync().ConfigureAwait(false);
                    await _context.ReceiveFault(context, ex).ConfigureAwait(false);
                }
                finally
                {
                    context.Dispose();
                }
            }
        }
开发者ID:MassTransit,项目名称:MassTransit,代码行数:47,代码来源:MessageSessionAsyncHandler.cs

示例4: CompleteProcessingMessageAsync

 /// <summary>
 /// This method completes processing of the specified message, after the job function has been invoked.
 /// </summary>
 /// <param name="message">The message to complete processing for.</param>
 /// <param name="result">The <see cref="FunctionResult"/> from the job invocation.</param>
 /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use</param>
 /// <returns>A <see cref="Task"/> that will complete the message processing.</returns>
 public virtual async Task CompleteProcessingMessageAsync(BrokeredMessage message, FunctionResult result, CancellationToken cancellationToken)
 {
     if (result.Succeeded)
     {
         if (!MessageOptions.AutoComplete)
         {
             // AutoComplete is true by default, but if set to false
             // we need to complete the message
             cancellationToken.ThrowIfCancellationRequested();
             await message.CompleteAsync();
         }
     }
     else
     {
         cancellationToken.ThrowIfCancellationRequested();
         await message.AbandonAsync();
     }
 }
开发者ID:JimAhles,项目名称:azure-webjobs-sdk,代码行数:25,代码来源:MessageProcessor.cs

示例5: WaitAndAbandonMessage

        async Task IMessageSessionAsyncHandler.OnMessageAsync(MessageSession session, BrokeredMessage message)
        {
            if (_receiver.IsShuttingDown)
            {
                await WaitAndAbandonMessage(message).ConfigureAwait(false);
                return;
            }

            var deliveryCount = _receiver.IncrementDeliveryCount();

            if (_log.IsDebugEnabled)
                _log.DebugFormat("Receiving {0}:{1}({3}) - {2}", deliveryCount, message.MessageId, _receiver.QueuePath, session.SessionId);

            var context = new ServiceBusReceiveContext(_receiver.InputAddress, message, _receiver.ReceiveObserver);
            context.GetOrAddPayload<MessageSessionContext>(() => new BrokeredMessageSessionContext(session));

            try
            {
                await _receiver.ReceiveObserver.PreReceive(context).ConfigureAwait(false);

                await _receiver.ReceivePipe.Send(context).ConfigureAwait(false);

                await context.CompleteTask.ConfigureAwait(false);

                await message.CompleteAsync().ConfigureAwait(false);

                await _receiver.ReceiveObserver.PostReceive(context).ConfigureAwait(false);

                if (_log.IsDebugEnabled)
                    _log.DebugFormat("Receive completed: {0}", message.MessageId);
            }
            catch (Exception ex)
            {
                if (_log.IsErrorEnabled)
                    _log.Error($"Received faulted: {message.MessageId}", ex);

                await message.AbandonAsync().ConfigureAwait(false);
                await _receiver.ReceiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);
            }
            finally
            {
                _receiver.DeliveryComplete();
            }
        }
开发者ID:kotvisbj,项目名称:MassTransit,代码行数:44,代码来源:MessageSessionAsyncHandler.cs

示例6: EventReceived

        private async Task EventReceived(BrokeredMessage m)
        {
            Trace.WriteLine("Message Event Received");

            var shouldAbandon = false;

            try
            {
                // TODO: Use reflection instead
                switch (m.ContentType)
                {
                    case "Models.ProtoBuf.Event":
                    {
                        // Deserialize Message
                        var msg = m.GetBody<Event>(_xpsEvent);
                        await ProcessEvent(msg);//.ConfigureAwait(false);
                        break;
                    }

                    case "Models.ProtoBuf.Command":
                    {
                        // Deserialize Message
                        var msg = m.GetBody<Command>(_xpsCommand);
                        await ProcessCommand(msg);//.ConfigureAwait(false);
                        break;
                    }
                }

                await m.CompleteAsync();//.ConfigureAwait(false);
            }
            catch
            {
                Trace.TraceError("Message Event Threw");

                // NOTE: Can't await inside a catch... yet
                shouldAbandon = true;

                // TODO: Handle message processing specific exceptions
            }

            if (shouldAbandon)
            {
                await m.AbandonAsync();//.ConfigureAwait(false);
            }
        }
开发者ID:baiyunping333,项目名称:BlazeDSP,代码行数:45,代码来源:WorkerRole.cs

示例7: WaitAndAbandonMessage

        async Task WaitAndAbandonMessage(BrokeredMessage message)
        {
            try
            {
                await _supervisor.Completed.ConfigureAwait(false);

                await message.AbandonAsync().ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (_log.IsErrorEnabled)
                    _log.Debug("Shutting down, abandoned message faulted: {_inputAddress}", exception);
            }
        }
开发者ID:JackWangCUMT,项目名称:MassTransit,代码行数:14,代码来源:Receiver.cs

示例8: OnMessage

        async Task OnMessage(BrokeredMessage message)
        {
            if (_shuttingDown)
            {
                await WaitAndAbandonMessage(message);
                return;
            }

            var current = Interlocked.Increment(ref _currentPendingDeliveryCount);
            while (current > _maxPendingDeliveryCount)
                Interlocked.CompareExchange(ref _maxPendingDeliveryCount, current, _maxPendingDeliveryCount);

            var deliveryCount = Interlocked.Increment(ref _deliveryCount);

            if (_log.IsDebugEnabled)
                _log.DebugFormat("Receiving {0}:{1} - {2}", deliveryCount, message.MessageId, _receiveSettings.QueueDescription.Path);

            var context = new ServiceBusReceiveContext(_inputAddress, message, _receiveObserver);

            try
            {
                await _receiveObserver.PreReceive(context).ConfigureAwait(false);

                await _receivePipe.Send(context).ConfigureAwait(false);

                await context.CompleteTask.ConfigureAwait(false);

                await message.CompleteAsync().ConfigureAwait(false);

                await _receiveObserver.PostReceive(context).ConfigureAwait(false);

                if (_log.IsDebugEnabled)
                    _log.DebugFormat("Receive completed: {0}", message.MessageId);
            }
            catch (Exception ex)
            {
                if (_log.IsErrorEnabled)
                    _log.Error($"Received faulted: {message.MessageId}", ex);

                await message.AbandonAsync().ConfigureAwait(false);
                await _receiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);
            }
            finally
            {
                var pendingCount = Interlocked.Decrement(ref _currentPendingDeliveryCount);
                if (pendingCount == 0 && _shuttingDown)
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Receiver shutdown completed: {0}", _inputAddress);

                    _participant.SetComplete();
                }
            }
        }
开发者ID:JackWangCUMT,项目名称:MassTransit,代码行数:54,代码来源:Receiver.cs

示例9: OnMessage

        async Task OnMessage(BrokeredMessage message)
        {
            int current = Interlocked.Increment(ref _currentPendingDeliveryCount);
            while (current > _maxPendingDeliveryCount)
                Interlocked.CompareExchange(ref _maxPendingDeliveryCount, current, _maxPendingDeliveryCount);

            long deliveryCount = Interlocked.Increment(ref _deliveryCount);

            if (_log.IsDebugEnabled)
                _log.DebugFormat("Receiving {0}:{1} - {2}", deliveryCount, message.MessageId, _receiveSettings.QueueDescription.Path);

            var context = new ServiceBusReceiveContext(_inputAddress, message, _receiveObserver);

            try
            {
                if (_shuttingDown)
                {
                    await _completeTask.Task.ConfigureAwait(false);

                    throw new TransportException(_inputAddress, "Transport shutdown in progress, abandoning message");
                }

                await _receiveObserver.PreReceive(context).ConfigureAwait(false);

                await _receivePipe.Send(context).ConfigureAwait(false);

                await context.CompleteTask.ConfigureAwait(false);

                await message.CompleteAsync().ConfigureAwait(false);

                await _receiveObserver.PostReceive(context).ConfigureAwait(false);

                if (_log.IsDebugEnabled)
                    _log.DebugFormat("Receive completed: {0}", message.MessageId);
            }
            catch (Exception ex)
            {
                if (_log.IsErrorEnabled)
                    _log.Error($"Received faulted: {message.MessageId}", ex);

                await message.AbandonAsync().ConfigureAwait(false);
                await _receiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);
            }
            finally
            {
                int pendingCount = Interlocked.Decrement(ref _currentPendingDeliveryCount);
                if (pendingCount == 0 && _shuttingDown)
                    _completeTask.TrySetResult(this);
            }
        }
开发者ID:lsfera,项目名称:MassTransit,代码行数:50,代码来源:Receiver.cs

示例10: Dispatch

        private async Task Dispatch(BrokeredMessage message)
        {
            // Early exit: have we pre-fetched this message and had our lock already expire? If so, just
            // bail - it will already have been picked up by someone else.
            if (message.LockedUntilUtc <= _clock.UtcNow)
            {
                GlobalMessageCounters.IncrementMessagesDroppedDueToExpiredLock(1);

                _logger.Debug("Lock for message {MessageId} appears to have already expired so we're not dispatching it. Watch out for clock drift between your service bus server and {MachineName}!", message.MessageId, Environment.MachineName);
                return;
            }

            try
            {
                Exception exception = null;

                try
                {
                    LogInfo("Dispatching", message);
                    using (_dispatchContextManager.StartNewDispatchContext(new SubsequentDispatchContext(message)))
                    {
                        await _taskFactory.StartNew(() => _messageDispatcher.Dispatch(message), TaskContext.Dispatch).Unwrap();
                    }
                    LogDebug("Dispatched", message);

                    LogDebug("Completing", message);
                    message.Properties[MessagePropertyKeys.DispatchComplete] = true;
                    await _taskFactory.StartNew(() => message.CompleteAsync(), TaskContext.CompleteOrAbandon).Unwrap();
                    LogInfo("Completed", message);

                    return;
                }

                catch (Exception exc)
                {
                    if (exc is MessageLockLostException || (exc.InnerException is MessageLockLostException))
                    {
                        _logger.Error(exc,
                                      "Message completion failed for {Type} from {QueuePath} [MessageId:{MessageId}, CorrelationId:{CorrelationId}]",
                                      message.SafelyGetBodyTypeNameOrDefault(),
                                      message.ReplyTo,
                                      message.MessageId,
                                      message.CorrelationId);
                        return;
                    }

                    _logger.Error(exc,
                                  "Message dispatch failed for {Type} from {QueuePath} [MessageId:{MessageId}, CorrelationId:{CorrelationId}]",
                                  message.SafelyGetBodyTypeNameOrDefault(),
                                  message.ReplyTo,
                                  message.MessageId,
                                  message.CorrelationId);

                    exception = exc;
                }

                try
                {
                    LogDebug("Abandoning", message);
                    message.Properties[MessagePropertyKeys.DispatchAbandoned] = true;
                    await message.AbandonAsync(exception.ExceptionDetailsAsProperties(_clock.UtcNow));
                    LogDebug("Abandoned", message);
                }
                catch (Exception exc)
                {
                    _logger.Error(exc,
                                  "Could not call Abandon() on message {Type} from {QueuePath} [MessageId:{MessageId}, CorrelationId:{CorrelationId}].",
                                  message.SafelyGetBodyTypeNameOrDefault(),
                                  message.MessageId,
                                  message.CorrelationId,
                                  message.ReplyTo);
                }
            }
            catch (Exception exc)
            {
                _logger.Fatal(exc, "Unhandled exception in message pump");
            }
        }
开发者ID:AtmosphereMessaging,项目名称:Cumulus,代码行数:78,代码来源:MessagePump.cs

示例11: Dispatch

        private async Task Dispatch(BrokeredMessage message)
        {
            try
            {
                Exception exception = null;

                try
                {
                    LogInfo("Dispatching", message);
                    using (_dispatchContextManager.StartNewDispatchContext(new DispatchContext(message)))
                    {
                        await _messageDispatcher.Dispatch(message);
                    }
                    LogDebug("Dispatched", message);

                    LogDebug("Completing", message);
                    await message.CompleteAsync();
                    LogInfo("Completed", message);

                    return;
                }
                catch (Exception exc)
                {
                    exception = exc;
                }

                _logger.Error(exception,
                              "Message dispatch failed for {0} from {1} [MessageId:{2}, CorrelationId:{3}]",
                              message.SafelyGetBodyTypeNameOrDefault(),
                              message.ReplyTo,
                              message.MessageId,
                              message.CorrelationId);

                try
                {
                    LogDebug("Abandoning", message);
                    await message.AbandonAsync(exception.ExceptionDetailsAsProperties(_clock.UtcNow));
                    LogDebug("Abandoned", message);
                }
                catch (Exception exc)
                {
                    _logger.Error(exc,
                                  "Could not call Abandon() on message {0} from {1} [MessageId:{2}, CorrelationId:{3}]. Possible lock expiry?",
                                  message.SafelyGetBodyTypeNameOrDefault(),
                                  message.MessageId,
                                  message.CorrelationId,
                                  message.ReplyTo);
                }
            }
            catch (Exception exc)
            {
                _logger.Error(exc, "Unhandled exception in message pump");
            }
        }
开发者ID:Joshscorp,项目名称:Nimbus,代码行数:54,代码来源:MessagePump.cs

示例12: ProcessMessageAsync

 private async Task ProcessMessageAsync(BrokeredMessage message, CancellationToken cancellationToken)
 {
     FunctionResult result = await _triggerExecutor.ExecuteAsync(message, cancellationToken);
     if (!result.Succeeded)
     {
         cancellationToken.ThrowIfCancellationRequested();
         await message.AbandonAsync();
     }
 }
开发者ID:Bjakes1950,项目名称:azure-webjobs-sdk,代码行数:9,代码来源:ServiceBusListener.cs

示例13: Dispatch

        private async Task Dispatch(BrokeredMessage message)
        {
            try
            {
                Exception exception = null;

                try
                {
                    _logger.Debug("Dispatching message: {0} from {1}", message, message.ReplyTo);
                    await _dispatcher.Dispatch(message);
                    _logger.Debug("Dispatched message: {0} from {1}", message, message.ReplyTo);

                    _logger.Debug("Completing message {0}", message);
                    await message.CompleteAsync();
                    _logger.Debug("Completed message {0}", message);

                    return;
                }
                catch (Exception exc)
                {
                    exception = exc;
                }

                _logger.Error(exception, "Message dispatch failed");

                try
                {
                    _logger.Debug("Abandoning message {0} from {1}", message, message.ReplyTo);
                    await message.AbandonAsync(exception.ExceptionDetailsAsProperties(_clock.UtcNow));
                    _logger.Debug("Abandoned message {0} from {1}", message, message.ReplyTo);
                }
                catch (Exception exc)
                {
                    _logger.Error(exc, "Could not call Abandon() on message {0} from {1}. Possible lock expiry?", message, message.ReplyTo);
                }
            }
            catch (Exception exc)
            {
                _logger.Error(exc, "Unhandled exception in message pump");
            }
        }
开发者ID:shingi,项目名称:Nimbus,代码行数:41,代码来源:MessagePump.cs

示例14: CancelRentalCar

        public static async Task CancelRentalCar(BrokeredMessage message, MessageSender nextStepQueue, MessageSender compensatorQueue)
        {
            try
            {
                var via = (message.Properties.ContainsKey("Via")
                    ? ((string) message.Properties["Via"] + ",")
                    : string.Empty) +
                          "cancelcar";

                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    if (message.Label != null &&
                        message.ContentType != null &&
                        message.Label.Equals(TravelBookingLabel, StringComparison.InvariantCultureIgnoreCase) &&
                        message.ContentType.Equals(ContentTypeApplicationJson, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var body = message.GetBody<Stream>();
                        dynamic travelBooking = DeserializeTravelBooking(body);

                        // do we want to book a flight? No? Let's just forward the message to
                        // the next destination via transfer queue
                        if (travelBooking.car != null &&
                            travelBooking.car.reservationId != null)
                        {
                            lock (Console.Out)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Cancelling Rental Car");
                                Console.ResetColor();
                            }

                            // undo the reservation (or pretend to fail)
                            if (DateTime.UtcNow.Second <= 3)
                            {
                                throw new Exception("O_o");
                            }

                            // reset the id
                            travelBooking.car.reservationId = null;

                            // forward
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                        }
                        else
                        {
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                        }
                        // done with this job
                        await message.CompleteAsync();
                    }
                    else
                    {
                        await message.DeadLetterAsync(
                            new Dictionary<string, object>
                                    {
                                        {"DeadLetterReason", "BadMessage"},
                                        {"DeadLetterErrorDescription", "Unrecognized input message"},
                                        {"Via", via}
                                    });
                    }
                    scope.Complete();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                await message.AbandonAsync();
            }
        }
开发者ID:Azure-Samples,项目名称:azure-servicebus-messaging-samples,代码行数:69,代码来源:TravelBookingHandlers.cs

示例15: BookFlight

        public static async Task BookFlight(BrokeredMessage message, MessageSender nextStepQueue, MessageSender compensatorQueue)
        {
            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var via = (message.Properties.ContainsKey("Via")
                        ? ((string) message.Properties["Via"] + ",")
                        : string.Empty) +
                              "bookflight";

                    if (message.Label != null &&
                        message.ContentType != null &&
                        message.Label.Equals(TravelBookingLabel, StringComparison.InvariantCultureIgnoreCase) &&
                        message.ContentType.Equals(ContentTypeApplicationJson, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var body = message.GetBody<Stream>();
                        dynamic travelBooking = DeserializeTravelBooking(body);


                        // do we want to book a flight? No? Let's just forward the message to
                        // the next destination via transfer queue
                        if (travelBooking.flight == null)
                        {
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                            // done with this job
                            await message.CompleteAsync();
                        }
                        else
                        {
                            lock (Console.Out)
                            {
                                Console.ForegroundColor = ConsoleColor.Cyan;
                                Console.WriteLine("Booking Flight");
                                Console.ResetColor();
                            }

                            // now we're going to simulate the work of booking a flight,
                            // which usually involves a call to a third party

                            // every 9th flight booking sadly goes wrong
                            if (message.SequenceNumber%9 == 0)
                            {
                                await message.DeadLetterAsync(
                                    new Dictionary<string, object>
                                    {
                                        {"DeadLetterReason", "TransactionError"},
                                        {"DeadLetterErrorDescription", "Failed to perform flight reservation"},
                                        {"Via", via}
                                    });
                            }
                            else
                            {
                                // every operation executed in the first 3 secs of any minute 
                                // tanks completely (simulates some local or external unexpected issue) 
                                if (DateTime.UtcNow.Second <= 3)
                                {
                                    throw new Exception("O_o");
                                }

                                // let's pretend we booked something
                                travelBooking.flight.reservationId = "A1B2C3";

                                await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                                // done with this job
                                await message.CompleteAsync();
                            }
                        }
                    }
                    else
                    {
                        await message.DeadLetterAsync(
                           new Dictionary<string, object>
                                    {
                                        {"DeadLetterReason", "BadMessage"},
                                        {"DeadLetterErrorDescription", "Unrecognized input message"},
                                        {"Via", via}
                                    });
                    }
                    scope.Complete();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                await message.AbandonAsync();
            }
        }
开发者ID:Azure-Samples,项目名称:azure-servicebus-messaging-samples,代码行数:88,代码来源:TravelBookingHandlers.cs


注:本文中的BrokeredMessage.AbandonAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。