1

我有一个简单的 C# 应用程序,它每秒向我的 RabbitMQ 交换发送一条消息。当我的互联网连接断开时,应用程序会崩溃。所以我添加了一个 Try/Catch 语句,现在它不再崩溃了。但是,当连接恢复时,它将不再发送数据。我必须关闭应用程序,然后重新打开它。我这样做正确吗?

   private void rabbitmqxmit()
    {
        try
        {
            while (rmqtxrun == true)
            {

                ConnectionFactory factory = new ConnectionFactory();
                factory.HostName = textBox3.Text;
                using (IConnection connection = factory.CreateConnection())
                using (IModel channel = connection.CreateModel())
                {


                    button1.BackColor = Color.Green;

                    string message = textBox1.Text;
                    byte[] body = System.Text.Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(textboxExchange.Text, textboxKey.Text, null, body);

                    txtboxTransmitting.Text = message;
                    button1.BackColor = Color.Gray;

                    Thread.Sleep(Convert.ToInt32(textBox4.Text));

                }


            }
        }
        catch {}
    }
4

2 回答 2

4

When the exception happens you're effectively exiting your loop. In order to get what you want to do you need to move your try/catch inside the while loop.

However, it'd be cleaner if you found a way to test the connection rather than expecting an exception. By simply taking any exception and dumping you're losing the ability to see other things potentially going wrong. Bare minimum I'd attempt to catch ONLY that exception that you expect to happen and log it someplace.

于 2013-03-23T21:36:41.223 回答
0

您可能必须重新初始化通道 - 尝试一下。由于 using 子句,连接和通道将被很好地处理掉。如果 ConnectionFactory 也实现了 IDisposable,那么也可以在 using 子句中创建它。

此外,捕获所有异常而不对它们做任何事情是一种非常糟糕的方法。更好的方法是只捕获连接异常。

于 2013-03-23T21:17:15.387 回答