Skip to content

Instantly share code, notes, and snippets.

@lomomike
Last active July 11, 2017 15:11
Show Gist options
  • Save lomomike/f21de9a3f47810331a9f83deb1cfbdae to your computer and use it in GitHub Desktop.
Save lomomike/f21de9a3f47810331a9f83deb1cfbdae to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
namespace TestRmqConnection
{
public class Program
{
public static void Main(string[] args)
{
var waitingTimeout = TimeSpan.FromMilliseconds(200);
int timeout;
if (args.Length > 1 && int.TryParse(args[1], out timeout))
{
waitingTimeout = TimeSpan.FromMilliseconds(timeout);
}
Console.WriteLine($"PID = {Process.GetCurrentProcess().Id}");
var tcs = new CancellationTokenSource();
var tasks = new Task[Environment.ProcessorCount];
for (int i = 0; i < Environment.ProcessorCount; i++)
{
var task = Task.Factory.StartNew(() => TryConnect(tcs.Token, waitingTimeout), tcs.Token, TaskCreationOptions.LongRunning,
TaskScheduler.Default);
tasks[i] = task;
}
Console.WriteLine("Press any key to exit");
Console.ReadLine();
tcs.Cancel();
Task.WaitAll(tasks);
}
private static void TryConnect(CancellationToken token, TimeSpan waitingTimeout)
{
var factory = new ConnectionFactory
{
Endpoint = new AmqpTcpEndpoint
{
HostName = "127.0.0.1",
Port = 8888 // Incorrect port
}
};
while (true)
{
if (token.IsCancellationRequested)
break;
try
{
var connection = factory.CreateConnection();
}
catch (BrokerUnreachableException e)
{
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Cannot connect to RabbitMq");
}
Thread.Sleep(waitingTimeout);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment