2

I am using multi threading concept to run some process. this process uses the sql connection object to get the data from database.This object is in another class. how to synchronize the sql connection while using multithreading?

2 Answers 2

2

Just create a new connection in each place you need it. Connection pooling will automatically ensure it only creates as many physical connections as you need.

using(var conn = new SqlConnection("..."))
{
    var cmd = new SqlCommand("...", conn);
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. Generate and destroy them as you go. Anything else - escept some very rare special orrurances, like only being allowed to use one connection for some external reason - is stupid and needlessly bogs speed down.
1

The easiest way will be to wrap the operation in a lock() clause...

lock(sharedConnection_)
{
  // do your operations here
}

You can probably find a way to not have to duplicate that lock all over the place. Anyway. If you do that, you will ensure that no two threads will hold a lock on the same object at the same time.

There are more sophisticated things you might do but this is a good start.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.