The first paragraph is very concise, but many people, including myself, can not help but have a few big questions:
1, how to parallel operation N Multiple database tutorials to share only one connection object?
2, parallel processing where the lock, every database operation to lock a bit (I feel that this is not playing the advantages of multithreading parallel processing, personally think it is not as fast as a single thread execution), this really is necessary?
3, the same database connection string, using the database connection object SqlConnection How to pass the ginseng, explicit open and close is not better? Usually not all by using a bit?
Now let's look at the code.
String sqlconnstring = @ "Data source=. SQLEXPRESS;
Attachdbfilename= "" E:dbnorthwnd.mdf "";
Integrated security=true; Connect timeout=30; User Instance=true ";
SqlConnection conn = new SqlConnection (sqlconnstring);
Conn. Open ();
Parallel.For (1, Int32.MaxValue, (ID) =>
{
ExecuteCommand (conn, id);
});
Among them, the concrete realization of ExecuteCommand is as follows:
private static Object syncobj = new Object ();
private static void ExecuteCommand (SqlConnection conn, int id)
{
Lock (Syncobj)
{
IF (Conn. State!= ConnectionState.Open)
{
Conn. Open ();
}
Console.WriteLine ("Executing." + ID);
Thread.Sleep (100);
SqlCommand cmd = new SqlCommand (
String. Format ("Insert into nums values (' {0} ')", ID), conn);
Cmd. ExecuteNonQuery ();
}
}
After a simple thought, the implementation code was improved on the local machine to test it as follows:
Parallel.For (1, Int32.MaxValue, (ID) =>
{
ExecuteCommand (ID);
});
The ExecuteCommand method no longer accepts the SqlConnection object as a parameter, removes the lock, and the database operation looks like a database operation, opening a database connection to ensure thread safety:
private static void ExecuteCommand (int id)
{
using SqlConnection conn = new SqlConnection (s qlconnstring))
{
conn. Open ();
Console.WriteLine ("Executing." + ID);
thread.sleep (100);
SqlCommand cmd = new SqlCommand (
string. Format ("Insert into nums values (' {0} ')", ID), conn);
cmd. ExecuteNonQuery ();
}
}
Of course ExecuteCommand can also be handled by explicit open and close:
private static void ExecuteCommand (int id)
{
SqlConnection conn = new SqlConnection (sqlconnstring);
Conn. Open ();
Console.WriteLine ("Executing." + ID);
Thread.Sleep (100);
SqlCommand cmd = new SqlCommand (
String. Format ("Insert into nums values (' {0} ')", ID), conn);
Cmd. ExecuteNonQuery ();
Conn. Close ();
}
According to my local machine test, the above improved two writing database connection objects to use normal, thread safety, and in performance than the lock operation database improved significantly, interested in you might as well try.