An exception was encountered today when doing SQL Concurrency update: (Code below)
// Parallel class can produce concurrent operations (i.e. multithreading) Parallel.ForEach (topics, topic ={ //DBHelper is a encapsulated database operation class, the following line of code executes the UPDATE statement "topicid=" + topic. TOPICID);});
This problem occurs because, in SQL Server by default, an SQL statement is a transaction. When multi-threaded simultaneous update, it will produce multiple transactions at the same time, a transaction waits for the end of B transaction, b transaction waits for a transaction to end, then causes the deadlock.
Workaround: Lock locking (that is, when multiple threads access the lock code area at the same time, only one thread is allowed to enter, and the other threads are in a wait state)
// declares a static read-only lock object static readonly object o = new object (); Parallel.ForEach (topics, topic =>{ / / lock lock (o) { // Only one thread at a time can enter Dbhelper.update (topic, " topicid= " + topic. TOPICID); }});
Small note: The transaction (Process ID 56) is deadlocked with another process on the lock | Communication buffer resource and has been selected as the deadlock victim.