本文整理汇总了C#中ITransactionContext.OnDisposed方法的典型用法代码示例。如果您正苦于以下问题:C# ITransactionContext.OnDisposed方法的具体用法?C# ITransactionContext.OnDisposed怎么用?C# ITransactionContext.OnDisposed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ITransactionContext
的用法示例。
在下文中一共展示了ITransactionContext.OnDisposed方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetConnection
Task<IDbConnection> GetConnection(ITransactionContext context)
{
return context
.GetOrAdd(CurrentConnectionKey,
async () =>
{
var dbConnection = await _connectionProvider.GetConnection();
context.OnCommitted(async () => await dbConnection.Complete());
context.OnDisposed(() =>
{
dbConnection.Dispose();
});
return dbConnection;
});
}
示例2: Receive
/// <summary>
/// Received the next available transport message from the input queue via MSMQ. Will create a new <see cref="MessageQueueTransaction"/> and stash
/// it under the <see cref="CurrentTransactionKey"/> key in the given <paramref name="context"/>. If one already exists, an exception will be thrown
/// (because we should never have to receive multiple messages in the same transaction)
/// </summary>
public async Task<TransportMessage> Receive(ITransactionContext context)
{
if (context == null) throw new ArgumentNullException("context");
if (_inputQueueName == null)
{
throw new InvalidOperationException("This MSMQ transport does not have an input queue, hence it is not possible to reveive anything");
}
var queue = GetInputQueue();
if (context.Items.ContainsKey(CurrentTransactionKey))
{
throw new InvalidOperationException("Tried to receive with an already existing MSMQ queue transaction - while that is possible, it's an indication that something is wrong!");
}
var messageQueueTransaction = new MessageQueueTransaction();
messageQueueTransaction.Begin();
context.OnCommitted(async () => messageQueueTransaction.Commit());
context.OnDisposed(() => messageQueueTransaction.Dispose());
context.Items[CurrentTransactionKey] = messageQueueTransaction;
try
{
var message = queue.Receive(TimeSpan.FromSeconds(1), messageQueueTransaction);
if (message == null)
{
messageQueueTransaction.Abort();
return null;
}
var headers = _extensionSerializer.Deserialize(message.Extension, message.Id);
var body = new byte[message.BodyStream.Length];
await message.BodyStream.ReadAsync(body, 0, body.Length);
return new TransportMessage(headers, body);
}
catch (MessageQueueException exception)
{
if (exception.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
{
return null;
}
if (exception.MessageQueueErrorCode == MessageQueueErrorCode.InvalidHandle)
{
_log.Info("Queue handle for '{0}' was invalid - will try to reinitialize the queue", _inputQueueName);
ReinitializeInputQueue();
}
if (exception.MessageQueueErrorCode == MessageQueueErrorCode.QueueDeleted)
{
_log.Warn("Queue '{0}' was deleted - will not receive any more messages", _inputQueueName);
return null;
}
throw new IOException(
string.Format("Could not receive next message from MSMQ queue '{0}'", _inputQueueName),
exception);
}
}
示例3: GetClientFromTransactionContext
private AmazonSQSClient GetClientFromTransactionContext(ITransactionContext context)
{
return context.GetOrAdd(ClientContextKey, () =>
{
var amazonSqsClient = new AmazonSQSClient(_accessKeyId, _secretAccessKey, new AmazonSQSConfig()
{
RegionEndpoint = _regionEndpoint
});
context.OnDisposed(amazonSqsClient.Dispose);
return amazonSqsClient;
});
}
示例4: Send
/// <summary>
/// Sends the given transport message to the specified destination address using MSMQ. Will use the existing <see cref="MessageQueueTransaction"/> stashed
/// under the <see cref="CurrentTransactionKey"/> key in the given <paramref name="context"/>, or else it will create one and add it.
/// </summary>
public async Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
{
if (destinationAddress == null) throw new ArgumentNullException("destinationAddress");
if (message == null) throw new ArgumentNullException("message");
if (context == null) throw new ArgumentNullException("context");
var logicalMessage = CreateMsmqMessage(message);
var messageQueueTransaction = context.GetOrAdd(CurrentTransactionKey, () =>
{
var messageQueueTransaction1 = new MessageQueueTransaction();
messageQueueTransaction1.Begin();
context.OnCommitted(async () => messageQueueTransaction1.Commit());
return messageQueueTransaction1;
});
var sendQueues = context.GetOrAdd(CurrentOutgoingQueuesKey, () =>
{
var messageQueues = new ConcurrentDictionary<string, MessageQueue>(StringComparer.InvariantCultureIgnoreCase);
context.OnDisposed(() =>
{
foreach (var messageQueue in messageQueues.Values)
{
messageQueue.Dispose();
}
});
return messageQueues;
});
var path = MsmqUtil.GetFullPath(destinationAddress);
var sendQueue = sendQueues.GetOrAdd(path, _ =>
{
var messageQueue = new MessageQueue(path, QueueAccessMode.Send);
return messageQueue;
});
sendQueue.Send(logicalMessage, messageQueueTransaction);
}
示例5: Receive
public async Task<TransportMessage> Receive(ITransactionContext context)
{
using (await _bottleneck.Enter())
{
var brokeredMessage = await ReceiveBrokeredMessage();
if (brokeredMessage == null) return null;
var headers = brokeredMessage.Properties
.Where(kvp => kvp.Value is string)
.ToDictionary(kvp => kvp.Key, kvp => (string)kvp.Value);
var messageId = headers.GetValueOrNull(Headers.MessageId);
_log.Debug("Received brokered message with ID {0}", messageId);
var leaseDuration = (brokeredMessage.LockedUntilUtc - DateTime.UtcNow);
var lockRenewalInterval = TimeSpan.FromMinutes(0.8 * leaseDuration.TotalMinutes);
var renewalTask = GetRenewalTaskOrFakeDisposable(messageId, brokeredMessage, lockRenewalInterval);
context.OnAborted(() =>
{
renewalTask.Dispose();
_log.Debug("Abandoning message with ID {0}", messageId);
try
{
brokeredMessage.Abandon();
}
catch (Exception exception)
{
// if it fails, it'll be back on the queue anyway....
_log.Warn("Could not abandon message: {0}", exception);
}
});
context.OnCommitted(async () =>
{
renewalTask.Dispose();
});
context.OnCompleted(async () =>
{
_log.Debug("Completing message with ID {0}", messageId);
await GetRetrier().Execute(() => brokeredMessage.CompleteAsync());
});
context.OnDisposed(() =>
{
renewalTask.Dispose();
_log.Debug("Disposing message with ID {0}", messageId);
brokeredMessage.Dispose();
});
return new TransportMessage(headers, brokeredMessage.GetBody<byte[]>());
}
}
示例6: Receive
public async Task<TransportMessage> Receive(ITransactionContext context)
{
if (_inputQueueAddress == null)
{
throw new InvalidOperationException("This Azure Service Bus transport does not have an input queue, hence it is not possible to reveive anything");
}
using (await _bottleneck.Enter())
{
var brokeredMessage = await ReceiveBrokeredMessage();
if (brokeredMessage == null) return null;
var headers = brokeredMessage.Properties
.Where(kvp => kvp.Value is string)
.ToDictionary(kvp => kvp.Key, kvp => (string)kvp.Value);
var messageId = headers.GetValueOrNull(Headers.MessageId);
var leaseDuration = (brokeredMessage.LockedUntilUtc - DateTime.UtcNow);
var lockRenewalInterval = TimeSpan.FromMinutes(0.8 * leaseDuration.TotalMinutes);
var renewalTask = GetRenewalTaskOrFakeDisposable(messageId, brokeredMessage, lockRenewalInterval);
context.OnAborted(() =>
{
renewalTask.Dispose();
try
{
brokeredMessage.Abandon();
}
catch (Exception exception)
{
// if it fails, it'll be back on the queue anyway....
_log.Warn("Could not abandon message: {0}", exception);
}
});
context.OnCommitted(async () => renewalTask.Dispose());
context.OnCompleted(async () =>
{
await brokeredMessage.CompleteAsync();
});
context.OnDisposed(() =>
{
renewalTask.Dispose();
brokeredMessage.Dispose();
});
using (var memoryStream = new MemoryStream())
{
await brokeredMessage.GetBody<Stream>().CopyToAsync(memoryStream);
return new TransportMessage(headers, memoryStream.ToArray());
}
}
}
示例7: Receive
/// <summary>
/// Receives the next message from the logical input queue by loading the next file from the corresponding directory,
/// deserializing it, deleting it when the transaction is committed.
/// </summary>
public async Task<TransportMessage> Receive(ITransactionContext context, CancellationToken cancellationToken)
{
string fullPath = null;
try
{
var fileNames = Directory.GetFiles(GetDirectoryForQueueNamed(_inputQueue), "*.rebusmessage.json")
.OrderBy(f => f)
.ToList();
var index = 0;
while (index < fileNames.Count)
{
fullPath = fileNames[index++];
// attempt to capture a "lock" on the file
if (_messagesBeingHandled.TryAdd(fullPath, new object()))
break;
fullPath = null;
}
if (fullPath == null) return null;
var jsonText = await ReadAllText(fullPath);
var receivedTransportMessage = Deserialize(jsonText);
string timeToBeReceived;
if (receivedTransportMessage.Headers.TryGetValue(Headers.TimeToBeReceived, out timeToBeReceived))
{
var maxAge = TimeSpan.Parse(timeToBeReceived);
var creationTimeUtc = File.GetCreationTimeUtc(fullPath);
var nowUtc = RebusTime.Now.UtcDateTime;
var messageAge = nowUtc - creationTimeUtc;
if (messageAge > maxAge)
{
try
{
File.Delete(fullPath);
return null;
}
finally
{
object _;
_messagesBeingHandled.TryRemove(fullPath, out _);
}
}
}
context.OnCompleted(async () => File.Delete(fullPath));
context.OnDisposed(() =>
{
object _;
_messagesBeingHandled.TryRemove(fullPath, out _);
});
return receivedTransportMessage;
}
catch (IOException)
{
if (fullPath != null)
{
object _;
_messagesBeingHandled.TryRemove(fullPath, out _);
}
return null;
}
}
示例8: GetModel
IModel GetModel(ITransactionContext context)
{
var model = context.GetOrAdd(CurrentModelItemsKey, () =>
{
var connection = _connectionManager.GetConnection();
var newModel = connection.CreateModel();
context.OnDisposed(() => newModel.Dispose());
return newModel;
});
return model;
}