views:

122

answers:

4

Hi All,

I've got a multithreaded C# 2.0 app where each thread writes some results into a SQL server 2000 database table. There is only a straight INSERT command and no other logic.

My question is - do I need to put a lock around the methods that writes the results to the database? There is a lock at the moment but I suspect that it's slowing down the app by quite a lot.

Thanks!

A: 

Since we're talking about MS SQL Server, I suppose they have internal lockings to prevent data corruption. Most modern DBMS would do that, otherwise they will have big trouble.

thephpdeveloper
+2  A: 

No you don't need any lock, but you need to create a new SqlConnection for each insert. The documentation says that instance members of SqlConnection are not threadsafe.

Edit2: By beeing NOT threadsafe in the case means that you can not have a single SqlConnection shared between several threads. But if each thread have its own SqlConnection the inserts are OK. The database itself adheres to the ACID properties and thus concurrent connections trying to insert data is safe and well defined.

Edit: But you should be careful when removing strange code if you can not figure out why it was written that way in the first place. It could easily have some kind of side effect that is non trivial to figure out by looking at just the database code. But on the other hand, if the code was written by someone who pasted some random code found through Google, then your best bet would be to rewrite the code anyway.

Albin Sunnanbo
Yes, this makes sense. I worte the code myself and put the locks everywhere where I had a slightest doubt. But now I am tuning performance by removing unnsesessery locks.
Misha
A: 

Are you changing some common state in the methods that write to the database? If the answer is NO, then you don't need to worry about the lock; you can remove it.

But is it really slowing your application? How many threads you are creating in your application?

saurabh
+6  A: 

As Suggested earlier "SqlConnection are not threadsafe".

Just try to Open the connection once during your application and MS SQL Server have there internal locking to prevent data lose so you need not to worry.

shrikant.soni
-1 This is actually a bad advice to use only one connection. You can not share the connection between threads and you need locking. Just what the OP was trying to avoid. Connection pooling assures that you get good performance when creating new connections for every insert.
Albin Sunnanbo
"Connection pooling assures that you get good performance when creating new connections for every insert." -- Are you serious?
zerkms
Yes, assuming there is only insert per "operation". Like in the case of a web application or similar inserting data in the database. Not in the case of a batch insert of several queued stuff, but then I don't think the application would be multi threaded in the first place.
Albin Sunnanbo