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


C# QueueClient.OnMessage方法代码示例

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


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

示例1: ReceiveQueueMessages

        static void ReceiveQueueMessages(QueueClient Client)
        {
            // Configure the callback options.
            OnMessageOptions options = new OnMessageOptions();
            options.AutoComplete = false;
            options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

            // Callback to handle received messages.
            Client.OnMessage((message) =>
            {
                try
                {
                    // Process message from queue.
                    Console.WriteLine("Body: " + message.GetBody<string>());
                    Console.WriteLine("MessageID: " + message.MessageId);
                    Console.WriteLine("Test Property: " +
                    message.Properties["TestProperty"]);

                    // Remove message from queue.
                    message.Complete();
                }
                catch (Exception)
                {
                    // Indicates a problem, unlock message in queue.
                    message.Abandon();
                }
            }, options);
            Console.ReadLine();
        }
开发者ID:aravindnet,项目名称:AzureServiceBusSample,代码行数:29,代码来源:Program.cs

示例2: Initialize

        public void Initialize(string queueName, string connectionString)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            QueueDescription queue;
            if (!namespaceManager.QueueExists(queueName))
            {
                queue = namespaceManager.CreateQueue(queueName);
                queue.EnableBatchedOperations = false;
                queue.EnableExpress = true;
                queue.DefaultMessageTimeToLive = TimeSpan.FromDays(3);
                //queue.EnableLargeMessages = true;
                queue.MaxDeliveryCount = int.MaxValue;
                //queue.RequiresSession = false;
                queue.SupportOrdering = true;
            }
            else
            {
                queue = namespaceManager.GetQueue(queueName);
            }

            queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName, ReceiveMode.PeekLock);
            queueClient.OnMessage(receivedMessage =>
            {
                try
                {
                    MessageReceived(receivedMessage);
                    Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());
                }
                catch (Exception exc)
                {
                    receivedMessage.Abandon();
                    Trace.TraceError(exc.ToString());
                }
            }, new OnMessageOptions { AutoComplete = false, MaxConcurrentCalls = 10000 });
        }
开发者ID:tamifist,项目名称:KinderChat,代码行数:35,代码来源:ServiceBusQueue.cs

示例3: Listen

		public void Listen()
		{
			_logger.Info("Starting Service Bus Listener.");

			string connectionString =
				CloudConfigurationManager.GetSetting("ServiceBus");

			_client = QueueClient.CreateFromConnectionString(connectionString, _queueName);

			_client.OnMessage(MessageHandler, new OnMessageOptions
			{
				AutoComplete = false,
				AutoRenewTimeout = TimeSpan.FromMinutes(5),
				MaxConcurrentCalls = 10
			});
		}
开发者ID:gbLabs,项目名称:tnLabs,代码行数:16,代码来源:ServiceBusMessageHandler.cs

示例4: HandleSingle

 private static void HandleSingle(QueueClient client)
 {
     client.OnMessage(msg =>
                      {
                          try
                          {
                              HandleMessage(msg);
                              msg.Complete();
                          }
                          catch (Exception)
                          {
                              Console.WriteLine("Error handling message -> Abandon");
                              msg.Abandon();
                          }
                      });
 }
开发者ID:spederiva,项目名称:AzureOss,代码行数:16,代码来源:Program.cs

示例5: Run

        public override void Run()
        {
            try
            {
                var nsManager = NamespaceManager.CreateFromConnectionString(CommonResources.ConnectionStrings.AzureServiceBus);
                if (!nsManager.QueueExists(QueueName))
                    nsManager.CreateQueue(QueueName);

                _client = QueueClient.CreateFromConnectionString(CommonResources.ConnectionStrings.AzureServiceBus, QueueName);
                _client.PrefetchCount = 10;

                var eventDrivenMessagingOptions = new OnMessageOptions
                {
                    AutoComplete = true,
                    MaxConcurrentCalls = 10
                };
                eventDrivenMessagingOptions.ExceptionReceived += OnExceptionReceived;

                Console.WriteLine(" > {0} - Sending {1} test messages", DateTime.Now, MsgsToSend);
                Stopwatch.Start();
                SendMessages();
                Stopwatch.Stop();
                Console.WriteLine(" > {0} - {1} of {2} sent in {3} ms", DateTime.Now, MsgsToSend, MsgsToSend, Stopwatch.ElapsedMilliseconds);

                Thread.Sleep(2000);
                Console.WriteLine(" > {0} - Recieving {1} test messages", DateTime.Now, MsgsToSend);
                Stopwatch.Restart();
                _client.OnMessage(OnMessageArrived, eventDrivenMessagingOptions);

                Console.WriteLine("Press any key to close connection");
            }
            catch (Exception ex)
            {
                Console.WriteLine(" > Exception received: {0}",
                    ex.Message);
            }
            finally
            {
                Console.ReadLine();
                _client.Close();
            }

            Console.WriteLine("Press any key to close application");
            Console.ReadLine();
        }
开发者ID:AtmosphereMessaging,项目名称:Cumulus-vNext,代码行数:45,代码来源:RawSdkImplementation.cs

示例6: ProcessAzureQueueMessage

        // https://azure.microsoft.com/sv-se/documentation/articles/websites-dotnet-webjobs-sdk-storage-queues-how-to/
        // This function will get triggered/executed when a new message is written on an Azure Queue called sqhealthmonitorqueue.
        // By default, the SDK gets a batch of 16 queue messages at a time and executes the function that processes them in parallel.
        public static void ProcessAzureQueueMessage([QueueTrigger("sqhealthmonitorqueue")] string p_message, TextWriter azureBlogLog, CancellationToken token)
        {
            // 1. Get StorageQueue message
            azureBlogLog.WriteLine(p_message); // logs the message to Blob storage log
            if (token.IsCancellationRequested)  // for Long processes, use CancellationToken
            {
                azureBlogLog.WriteLine("Function was cancelled at iteration");
                return;
            }
            // Process the storageQueue message... maybe a long time
            Utils.Logger.Debug("ReceivedStorageQueueMessage: " + p_message);

            // 2. Send Service BusQueue message
            if (gBusQueueClient == null)
            {
                string azureServiceBusKN = Encoding.UTF8.GetString(Convert.FromBase64String(ConfigurationManager.ConnectionStrings["HQHealthMonitor.AzureServiceBusKN"].ConnectionString));
                string azureServiceBusK = Encoding.UTF8.GetString(Convert.FromBase64String(ConfigurationManager.ConnectionStrings["HQHealthMonitor.AzureServiceBusK"].ConnectionString));
                Utils.Logger.Debug("AzureServiceBusConnectionName and key: " + azureServiceBusKN + ":" + azureServiceBusK);
                // this fast MessagingFactory implementation is in Microsoft.ServiceBus.Messaging.Configuration.KeyValueConfigurationManager

                // MessagingFactory.CreateFromConnectionString(connectionString, true) true = useCache; Cache used for creating the MessagingFactor, so next time you don't have to.
                // MessagingFactory CreationCache is not used, MessagingFactory is deleted and recreated every time this Function is called.
                // So, my SLOW version was slow, because MessagingFactory creation is very slow = 200-500msec. And I created it every time. First time.
                // However, when the created Factory was in the cache, we don't have to create it before every Send operation.
                // solution: create once and store it in memory
                TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(azureServiceBusKN, azureServiceBusK); // SAS: latency is 250msec or more
                MessagingFactorySettings mfs = new MessagingFactorySettings();
                mfs.TokenProvider = tokenProvider;
                //mfs.TransportType = TransportType.Amqp;       // 600msec latency
                mfs.TransportType = TransportType.NetMessaging;     // 230msec latency
                mfs.NetMessagingTransportSettings.BatchFlushInterval = TimeSpan.Zero;  // instead of 20msec, // latency is 37msec was the minimum I measured (instead of 43msec)
                //mfs.NetMessagingTransportSettings.BatchFlushInterval = TimeSpan.FromMilliseconds(20);  // instead of 20msec
                MessagingFactory factory = MessagingFactory.Create("sb://sqhealthmonitorservicebusqueue-ns.servicebus.windows.net/", mfs);
                gBusQueueClient = factory.CreateQueueClient("SQHealthMonitorServiceBusQueue", ReceiveMode.PeekLock);
                gBusQueueClient.PrefetchCount = 0;  // it is the default too, and it was 0 in the fast and in the slow cases too

                //gBusQueueClient = QueueClient.CreateFromConnectionString(azureServiceBusConnectionString, "SQHealthMonitorServiceBusQueue");  // latency is 43msec was the minimum I measured

                // Callback to handle received messages.
                // 3. Receive BusQueue message
                OnMessageOptions options = new OnMessageOptions();   // Configure the callback options.
                options.AutoComplete = false;
                options.AutoRenewTimeout = TimeSpan.FromMinutes(1);
                gBusQueueClient.OnMessage((receivedMessage) =>
                {
                    try
                    {
                        //Service Bus Queue performance: from StorageQueue vs ServiceBusQueue vs. EventHub.txt
                        //> first message arrives after 650msec // +GetBody() takes 150msec
                        //> next messages arrives in 39, 45, 60 msec.Great ! because we don't poll it every 5 seconds. Great subscriber model.
                        long highResReceivedTimeTick = System.Diagnostics.Stopwatch.GetTimestamp();   // this gives back UTC timestamp. Checked.

                        DateTime receivedTime = DateTime.UtcNow;
                        Utils.Logger.Debug("BusQueue message was received.");  // this takes 100msec
                        string messageBody = receivedMessage.GetBody<string>();

                        //Utils.Logger.Debug("BusQueue message.GetBody(): " + messageBody + "/" + receivedMessage.MessageId + "/" + receivedMessage.Properties["TestProperty"]);
                        Utils.Logger.Debug("BusQueue message.GetBody(): " + messageBody); // this takes 100msec

                        int separatorPos = messageBody.IndexOf(',');
                        if (separatorPos != -1)
                        {
                            string sentDateTimeStr = messageBody.Substring(0, separatorPos);
                            DateTime sentTime;
                            if (DateTime.TryParse(sentDateTimeStr, out sentTime))
                            {
                                int separatorPosTick = messageBody.IndexOf(',', separatorPos + 1);
                                if (separatorPosTick != -1)
                                {
                                    string highResSentDateTimeStr = messageBody.Substring(separatorPos + 1, separatorPosTick - separatorPos - 1);
                                    long highResSentTimeTick;
                                    if (Int64.TryParse(highResSentDateTimeStr, out highResSentTimeTick))
                                    {
                                        long elapsedTicks = highResReceivedTimeTick - highResSentTimeTick;
                                        long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
                                        long totalNanoSeconds = elapsedTicks * nanosecPerTick;
                                        long totalMiliseconds = totalNanoSeconds / 1000L / 1000L;
                                        Utils.Logger.Debug("BusQueue message was received in " + (receivedTime - sentTime).ToString() + " in highResTick as msec:" + totalMiliseconds);
                                    }
                                }
                            }
                        }
                        receivedMessage.Complete(); // Remove message from queue. Only send Complete(), when we are confident that we could send at least 1 email/SMS/phonecall to the user. We have 5 minutes to do that, because BusQueue LockDuration is 5 minutes maximum. After that message goes back to the queue (or Dead?)
                    }
                    catch (Exception ex)
                    {
                        Utils.Logger.Error(ex, "BusQueue message was received, but crash occured: " + ex.Message);
                        receivedMessage.Abandon();  // Indicates a problem, unlock message in queue.
                    }
                }, options);

            }

            // Performance Measurement:
            // Note: Usually the system clock (which is where DateTime.Now gets its data from) has a resolution of around 10-15ms.
            // The problem with DateTime when dealing with milliseconds isn't due to the DateTime class at all, but rather, has to do with CPU ticks and thread slices. Essentially, when an operation is paused by the scheduler to allow other threads to execute, it must wait at a minimum of 1 time slice before resuming which is around 15ms on modern Windows OSes.
            //Someone suggested to look at the Stopwatch class. Although the Stopwatch class is very accurate it does not tell me the current time, something i need in order to save the state of my program.
//.........这里部分代码省略.........
开发者ID:gyantal,项目名称:SQHealthMonitor,代码行数:101,代码来源:Functions.cs


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