views:

272

answers:

1

Hi,

I need to execute some Sql server stored procs in a thread safe manner. At the moment I'm using software locks (C# locks) to achieve this but wonder what kind of features provided by the Sql server itself to achieve thread safety. It seems to be there are some table and row locking features built in to Sql server.

Also from a performance perspective what is best approach? Software locks? Or Sql Server built in locks?

Thanks, Shamika

+3  A: 

The threads at your client are going to have very little to do with your database behavior. SQL Server is a multi-user database, so anyone can be doing anything to the database on a different machine at the same time, and all the thread-safety in the world is not going to help with that. SQL Server will use locks to maintain the database during transactions, to ensure that ACID rules and all your database constraints are maintained.

Typically, when you execute stored procedures on a single machine on the same thread, they will be sequential and cannot conflict. If you have multiple threads or use the async features of ADO.NET, then the procedures could conceivably interfere with each other within the SQL Server - i.e. blocking or deadlocking - but SQL Server is going to handle all that. Obviously, in this scenario, any code you have around them in your app needs to be threadsafe - i.e. you can't use the same IAsyncResult handle for both requests, you need to ensure that both threads are not attempting to modify the same data as a result of the completions, etc.

You need to lay out your requirements a bit more clearly, because these are two completely different locking scenarios.

Cade Roux
In the simplest stored procedure in my app, before adding a new record to a table I first check the existence. I need to do this in a thread safe manner.
Shamika
@Shamika - that's not going to be a threadsafety problem unless another thread would be inserting the same row (why would your application be doing that?).
Cade Roux
The data I'm inserting to the database I'm getting from an external database for which I don't have any control. Even though I'm supposed to get unique key fields from the external DB I found that sometimes it is not the case. So before inserting these record to my database I need to do this unique key validation. Data insertion is multi threaded.
Shamika
@Shamika I would simply handle that in your stored procedure in a simple IF NOT EXISTS (INSERT) within a transaction, and set an appropriate unique constraint on the table. No need to mess with threading in your app.
Cade Roux