AwkwardCoder
AwkwardCoder

Reputation: 25631

How do I share a transaction across a set of parallel tasks

I have a TransactionScope object and I want to use it for all the tasks created using Parallel.ForEach, how do I achieve this?

I want to writing to a message queue in parallel, 20-50 messages, message queue is transactional:

 using (var queue = new MessageQueue(_exportEndpoint))
 {
      var label = string.Format("{0} ComponentId - {1}", DateTime.Now.ToUniversalTime(), componentId);
      queue.Send(contents, label, MessageQueueTransactionType.Automatic);
      _log.WriteInfo("ExportToQueue: Message sent to queue - " + label);
 }

And the main thread is using a TransactionScope object, I tried the following but I get a time out on the commit of the transaction:

var clone = Transaction.Current.DependentClone(DependentCloneOption.RollbackIfNotComplete);
Parallel.ForEach(components.ToList(), c => ExportComponent(c, clone));

Upvotes: 4

Views: 2086

Answers (2)

AwkwardCoder
AwkwardCoder

Reputation: 25631

sorted!

I was missing a Complete for the DependentTransaction

Upvotes: 2

Ken
Ken

Reputation: 21

As long as those tasks participate individually with the transaction context, it is transparent. In other words, wrap your foreach with the transaction scope and you are done.

Upvotes: 0

Related Questions