protected CancellationTokenSource Subscribe(string queue, Func <BasicDeliverEventArgs, bool> function, CancellationTokenSource tokenSource = null) { if (String.IsNullOrWhiteSpace(queue)) { throw new ArgumentNullException(nameof(queue)); } var cancellationTokenSource = tokenSource ?? new CancellationTokenSource(); if (cancellationTokenSource.IsCancellationRequested) { throw new OperationCanceledException("Subscription has been cancelled by token", cancellationTokenSource.Token); } var connection = ConnectionPool.Take(ConnectionUri); var channel = connection.CreateModel(); var subscription = SubscriptionPool.Create(channel, queue); Task.Factory.StartNew(() => { var fn = function; var ct = cancellationTokenSource; var s = subscription; while (!ct.IsCancellationRequested) { if (subscription == null || !subscription.Next(TIMEOUT, out BasicDeliverEventArgs args)) { continue; } if (args == null) { cancellationTokenSource.Cancel(); continue; } if (fn(args)) { s.Ack(args); } } }, cancellationTokenSource.Token) .ContinueWith(t => /* метод будет выполнен в результате срабатывания cancellationTokenSource - нельзя делаеть его зависимым от токена */ { var uri = ConnectionUri; var c = connection; var ch = channel; var s = subscription; SubscriptionPool.Remove(s); ch.Close(); ConnectionPool.Return(uri, c); }); return(cancellationTokenSource); }
public static void Execute(string uri, Action <IConnection> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } var connection = ConnectionPool.Take(uri); try { action.Invoke(connection); } finally { ConnectionPool.Return(uri, connection); } }
public static void Execute(string uri, Action <IModel> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } var connection = ConnectionPool.Take(uri); try { using (var channel = connection.CreateModel()) { action.Invoke(channel); } } finally { ConnectionPool.Return(uri, connection); } }
public static BasicGetResult ExecuteAndReturn(string uri, Func <IModel, BasicGetResult> function) { if (function == null) { throw new ArgumentNullException(nameof(function)); } var connection = ConnectionPool.Take(uri); try { using (var channel = connection.CreateModel()) { return(function.Invoke(channel)); } } finally { ConnectionPool.Return(uri, connection); } }
private IConnection TakeConnection() { OnTakeConnection?.Invoke(typeof(AmqpHelper), new EventArgs()); return(ConnectionPool.Take(ConnectionUri)); }