简体   繁体   中英

Database table remains locked, if client process is killed after transaction start

I have a C# application which manipulates data in a table within a SQL Server database using transactions. The code is very simple and basically goes like this:

 public string ConnectionString;
 public OleDbConnection DbConnection;
 public OleDbTransaction DbTransaction;

 // ... some initialization stuff ...

 DbTransaction = DbConnection.BeginTransaction();
 try 
 {
     // ... some insert/update/delete here ...
     DbTransaction.Commit();
 } 
 catch (Exception e)
 {
      // ...
      DbTransaction.Rollback();
 }

Now, a situation was reported by a customer, that the table/rowset remained locked, while there was no active application instance running. His first guess was, that an error occurred during the transaction and no try-catch-block with a rollback is there (but this is definitely not the case, since there is a proper error handling). I can reproduce the situation, if I set a break point in the debugger before DbTransaction.Commit(); and then kill the process from Windows Task Manager. Then the transaction remains open (I can see it running DBCC OPENTRAN ) and a lock remains, which prohibits further working with a new instance of the application.

My question: How can I safely handle a situation like this - the process is killed after transaction start and has no chance to commit/rollback the transaction? As far as I know, I cannot recognize, if the application is being killed from the Task Manager ("Process" tab). So can I somehow automatically abort the transaction (eg after some timeout) or what else can I do? Please help.

maybe you should

SET XACT_ABORT ON 

so the sql server automatically rolls back the current transaction in case of an error.

http://technet.microsoft.com/de-de/library/ms188792.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM