本頁是否能提供幫助?
您對此內容的意見反應十分重要。 請告訴我們您的想法。
其他意見反應?
剩餘 1500 個字元
步驟 4:從佇列接收訊息

步驟 4:從佇列接收訊息

更新日期: 2015年6月

這是 服務匯流排 訊息功能教學課程中的第四個步驟。在此步驟中,您取得前一個步驟所建立佇列中的訊息清單。

  1. Queue() 方法中,逐一查看佇列,並使用 Microsoft.ServiceBus.Messaging.QueueClient.Receive 方法來接收訊息 (將每則訊息列印至主控台)。請將下列程式碼直接新增至前一個步驟中新增的程式碼下方:

    Console.WriteLine("Now receiving messages from Queue.");
    BrokeredMessage message;
    while ((message = myQueueClient.Receive(new TimeSpan(hours: 0, minutes: 1, seconds: 5))) != null)
        {
            Console.WriteLine(string.Format("Message received: {0}, {1}, {2}", message.SequenceNumber, message.Label, message.MessageId));
            message.Complete();
    
            Console.WriteLine("Processing message (sleeping...)");
            Thread.Sleep(1000);
        }
    

  1. 直接在先前新增的程式碼下方,新增下列程式碼,以清理訊息 Factory 和佇列資源:

    factory.Close();
    myQueueClient.Close();
    namespaceClient.DeleteQueue("IssueTrackingQueue");
    

  1. 最後一個步驟是新增可從 Main() 方法呼叫 Queue() 方法的陳述式。請在 Main() 結尾新增下列反白顯示的程式碼行:

    public static void Main(string[] args)
    {
        // Collect user input
        CollectUserInput();
    
        // Populate test data
        issues = ParseCSVFile();
        MessageList = GenerateMessages(issues);
    
        // Add this call
        Queue();
    }
    

範例

下列程式碼包含完整 QueueSample 應用程式。

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading;
using Microsoft.ServiceBus.Messaging;

namespace Microsoft.ServiceBus.Samples
{
  class Program
  {
    private static DataTable issues;
    private static List<BrokeredMessage> MessageList;
    private static string ServiceNamespace;
    private static string sasKeyName = "RootManageSharedAccessKey";
    private static string sasKeyValue;

    static void Main(string[] args)
    {
      // Populate test data
      issues = ParseCSVFile();
      MessageList = GenerateMessages(issues);

      // Collect user input
      CollectUserInput();

      // Add this call
      Queue();
    }

    static void Queue()
    {
      // Create management credentials
      TokenProvider credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(sasKeyName, sasKeyValue);
      NamespaceManager namespaceClient = new NamespaceManager(ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty), credentials);

      QueueDescription myQueue;
      myQueue = namespaceClient.CreateQueue("IssueTrackingQueue");

      MessagingFactory factory = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty), credentials);
      QueueClient myQueueClient = factory.CreateQueueClient("IssueTrackingQueue");

      // Send messages
      Console.WriteLine("Now sending messages to the Queue.");
      for (int count = 0; count < 6; count++)
      {
        var issue = MessageList[count];
        issue.Label = issue.Properties["IssueTitle"].ToString();
        myQueueClient.Send(issue);
        Console.WriteLine(string.Format("Message sent: {0}, {1}", issue.Label, issue.MessageId));
      }

      Console.WriteLine("Now receiving messages from Queue.");
      BrokeredMessage message;
      while ((message = myQueueClient.Receive(new TimeSpan(hours: 0, minutes: 1, seconds: 5))) != null)
      {
        Console.WriteLine(string.Format("Message received: {0}, {1}, {2}", message.SequenceNumber, message.Label, message.MessageId));
        message.Complete();

        Console.WriteLine("Processing message (sleeping...)");
        Thread.Sleep(1000);
      }

      factory.Close();
      myQueueClient.Close();
      namespaceClient.DeleteQueue("IssueTrackingQueue");
    }

    static DataTable ParseCSVFile()
    {
      DataTable tableIssues = new DataTable("Issues");
      string path = @"..\..\data.csv";
      try
      {
        using (StreamReader readFile = new StreamReader(path))
        {
          string line;
          string[] row;

          // create the columns
          line = readFile.ReadLine();
          foreach (string columnTitle in line.Split(','))
          {
            tableIssues.Columns.Add(columnTitle);
          }

          while ((line = readFile.ReadLine()) != null)
          {
            row = line.Split(',');
            tableIssues.Rows.Add(row);
          }
        }
      }
      catch (Exception e)
      {
        Console.WriteLine("Error:" + e.ToString());
      }

      return tableIssues;
    }

    static List<BrokeredMessage> GenerateMessages(DataTable issues)
    {
      // Instantiate the brokered list object
      List<BrokeredMessage> result = new List<BrokeredMessage>();

      // Iterate through the table and create a brokered message for each row
      foreach (DataRow item in issues.Rows)
      {
        BrokeredMessage message = new BrokeredMessage();
        foreach (DataColumn property in issues.Columns)
        {
          message.Properties.Add(property.ColumnName, item[property]);
        }
        result.Add(message);
      }
      return result;
    }

    static void CollectUserInput()
    {
      // User service namespace
      Console.Write("Please enter the service namespace to use: ");
      ServiceNamespace = Console.ReadLine();

      // Issuer key
      Console.Write("Please enter the issuer key to use: ");
      sasKeyValue = Console.ReadLine();
    }
  }
}




















































































































































Microsoft 正展開一份線上問卷調查,了解您對於 MSDN 網站的看法。 如果您選擇參加,您離開 MSDN 網站時即會顯示線上問卷調查。

您是否想要參加?
顯示:
© 2015 Microsoft