Share via

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

奇 卢 181 Reputation points
2021-08-11T12:24:14.547+00:00
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?

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


1 answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,611 Reputation points
    2021-08-12T06:27:25.077+00:00

    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.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.