frosty
frosty

Reputation: 5370

nhibernate retry how to manage the session in deadlocks

I have been having deadlock issues. I've been on working some retry approaches. My retry code is currently just a 'for' statement that tries 5 times. I understand i need to use the 'Evit' nhibernate method to clear the session. I am using a session factory and use a transaction for each request.

In the below example if i experience a deadlock on the first retry will the orderNote property remain the same on the second retry?

private ActionResult OrderDetails(int id)
{
    var order = _orderRepository.Get(id);
    order.OrderNote = "will this text remain";

    Retry.Times(5).Do(() => _orderRepository.Update(order));

    return View();
}

Edit

1) Finding it hard to trace the cause. I'm getting about 10 locks a day all over my application. Just set up a profiler. Are there any other useful methods for tracing

http://msdn.microsoft.com/en-us/library/ms190465.aspx

I think the main issue is that i'm using auto increament. I'm in the process of moving to hilo.

2) Using a different transation mode. I'm not defining any at the moment. What is recommended.

5) Long running operations. Yes i do. And i think because i'm using auto increament lazy loading is ignored. Does that sound correct?

Upvotes: 0

Views: 1591

Answers (1)

Mark Perry
Mark Perry

Reputation: 1735

In my opinion your code is trying to fix the symptoms instead of the cause.

You will be better off doing some of the following things:

  1. Find out why you are getting deadlocks and fix the core issue
  2. Use a different transaction mode to read past locks
  3. Look at delegating the update into a queue structure to be background processed
  4. Understand the update execution plan and perhaps add indexing to speed up queries
  5. Do you have any "long" running operations in your Controller action which is keeping the transaction open for longer than it should be?
  6. Even if the operation did deadlock, why don't you return an friendly error back to the calling page and let them manually retry.

Update:

1.) Useful methods for tracing

I have used this method for tracing deadlocks which should give you an idea of the resources which are in contention: Tracing Deadlocks

You can also look at the concurreny models available to you: NHibernate Concurrency

2.) Transaction Isolation Levels

Depending on your DB this Question has some useful information: Transaction Isolation Mode

3.) Long Running Operations

I have to use Identity Columns as my primary keys in NHibernate and I don't think these are going to be source of your problem in an update scenario as the Id/PK is already set by this point. Try to minimise the long running operations which will shorten the amount of time your transaction is held open.

Upvotes: 3

Related Questions