Reputation: 81
I have a simple C# application that is sending a message to my RabbitMQ exchange once every second. When my internet connection drops, the app would crash. So I added a Try/Catch statement and now it no longer crashes. But, when the connection is restored, it will not send data anymore. I have to close the app, and re-open it. Am I doing this correctly?
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 {}
}
Upvotes: 2
Views: 4198
Reputation: 13972
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.
Upvotes: 4
Reputation: 21458
You probably have to reinitialize the channel - try that. The connection and the channel will be disposed of in a nice way because of the using clause. If the ConnectionFactory also implements IDisposable, create it in a using clause as well.
Also, it's a very bad approach to catch all exceptions and not do anything with them. A better approach would be to catch just the connection exception.
Upvotes: 0