Argos
Argos

Reputation: 712

Should ServiceBroker conversations be inside a transaction

We have some code that looks a bit like this (error handling and other things removed)

using (var tran = conn.BeginTransaction())
{
    var client = new Service(...);
    var dialog = client.GetConversation(null, conn, tran);
    var response = dialog.Receive();

    // do stuff with response, including database work

    dialog.Send(message, conn, tran);
    dialog.EndConversation(conn, tran);

    tran.Commit();
    conn.Close();
}

We've inherited this code and aren't experts in ServiceBroker, would there be problems if we moved the conversation outside of the transaction like this:

var client = new Service(...);
var dialog = client.GetConversation(null, conn, tran);
var response = dialog.Receive();

using (var tran = conn.BeginTransaction())
{
    // do stuff with response, including database work
    tran.Commit();
}

dialog.Send(message, conn, tran);
dialog.EndConversation(conn, tran);
conn.Close();

Upvotes: 1

Views: 357

Answers (1)

Jānis
Jānis

Reputation: 2266

In this case you receive message and its gets removed from the queue. You will not be able to receive it again..

If all code is in transaction and there is error in message processing- transaction never commits and message stays in queue (by default- after 5 rollbacks queue gets disabled). So you can detect the reason of error, correct it and process message again (expected exceptions should not cause rollback, there are quite a few ways to handle them).

I would say that everything should be in transaction.

Upvotes: 1

Related Questions