2017-08-28 17 views
0

我有以下代碼,我試圖排隊負載的消息在我的rabbitmq隊列來測試它,看看我是否可以打破它。我不明白爲什麼它不工作:使循環工作在C銳利和排隊消息在RabbitMQ

我想在循環中做的是讓它發佈消息4次,然後完成。這段代碼中的錯誤是什麼?

代碼:

using System; 
using RabbitMQ.Client; 
using System.Text; 

class Send 
{ 
    public static void Main() 
    { 
     var factory = new ConnectionFactory() { HostName = "localhost" }; 
     using (var connection = factory.CreateConnection()) 
     { 
      using (var channel = connection.CreateModel()) 
      { 
       // for (int myInt = 0; myInt < 699;) 

       int myInt = 1; 
       do 
       while (myInt <= 4) 
       { 
        // channel.QueueDeclare("test", false, false, false, null); 
        //int myInt = 0; 
        //while (myInt < 10) ; 
        string message = "Hello World!"; 
        var body = Encoding.UTF8.GetBytes(message); 
        channel.BasicPublish("", "test", null, body); 
        Console.WriteLine(" [x] Sent {0}", message); 
        Console.Read(); 
        //Environment.Exit(0); 
        return; 
       } 
       //myInt++; 

      } 
     } 
    } 
} 

我的代碼更新爲:

using System; 
using RabbitMQ.Client; 
using System.Text; 

class Send 
{ 
    public static void Main() 
    { 
    var factory = new ConnectionFactory() { HostName = "localhost" }; 
    using (var connection = factory.CreateConnection()) 

    { for (int myInt = 100; myInt <= 100000 ; myInt++) 
      using (var channel = connection.CreateModel()) 


      while (myInt <= 100000) 
       { 
        string message = "Hello World!"; 
        var body = Encoding.UTF8.GetBytes(message); 
        channel.BasicPublish("", "hello", null, body); 
        Console.WriteLine(" [x] Sent {0}", message); 
        Console.Read(); 
        myInt++; 
       } 


       //myInt++; 
      } 
     //myInt++; 
    //return; 
     // myInt++; 
    } 

} 

但它仍然沒有工作。

+1

我不明白「它不工作」的意思。發佈[mcve]或至少實際與預期結果。 –

+2

第一次循環運行時,你從'Main()'返回' –

回答

1

您將return語句放在while循環中,這會導致程序在循環的一次迭代後終止。此外,您忘記增加變量myInt,因此即使您移動return語句,也會遇到無限循環的問題。另外,您不需要do關鍵字。 while循環應該是這個樣子:

while (myInt <= 4) 
    {  
     string message = "Hello World!"; 
     var body = Encoding.UTF8.GetBytes(message); 
     channel.BasicPublish("", "test", null, body); 
     Console.WriteLine(" [x] Sent {0}", message); 
     Console.Read(); 
     myInt++; 
    } 

以及返回的說法應該是在Main函數的最後一行。

+0

非常感謝的人。 – anallyexcel

+0

沒問題。乾杯! –