question

58901228 avatar image
0 Votes"
58901228 asked Viorel-1 commented

There is an error in using multithreading to write to the database. How to solve it?

 SqlCommand cmd = new SqlCommand(str, con);
 cmd.ExecuteNonQuery();

I use multiple threads for insert operation, but an error will occur at some time. Is it because all threads share a SqlConnection? How to solve it?

dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Simply use a new SqlConnection for each operation and have the connection string available for each in a central variable.

2 Votes 2 ·

Maybe it is not a problem that is caused by SqlConnection only. Show the error message and details.


0 Votes 0 ·

1 Answer

TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered

Do not share connections among multiple threads.

Create a SqlConnection object for each of your queries, and wrap it with a using statement to close it in time after the execution ends.

.NET, the SqlConnection object, and multi-threading

Using the same open SQL connection from different threads


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.