J R B
J R B

Reputation: 2136

Throwing exception when inserting data in C#

I am getting below warning when i inserting data.

Parallel.ForEach(user, data => Db.ExecuteQuery("insert into temptbl (userid,attflag,checktime,username)values('" +
                                                                     data.UserId + "','" + data.Flag + "','" + data.AttendanceDate + "','" +
                                                                     data.Name + "')"));

enter image description here

Upvotes: 0

Views: 281

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391466

Database connection objects are not thread-safe and are not meant to be used in multiple threads at the same time.

You should not parallelize the code across a single connection, instead you will need a separate connection for each distinct thread, and thus you cannot use Parallel.ForEach.

You can see this documented on MSDN:

OleDbConnection Class, Thread Safety section (near the bottom):

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

This means that static members of this type are thread-safe, instance-members are not, which means that the type as an object will not be thread-safe.

Upvotes: 4

Related Questions