没什么的,最主要的是每个线程肯定有一个独立的Connection。
class SqlExecutor
{
private string connectionString;
private string commandText;
private Thread workthread;
public SqlExecutor(string commandText, string connectionString)
{
this.commandText = commandText;
this.connectionString = connectionString;
}
public void DoExecute()
{
workthread = new Thread(new ThreadStart(this.ExecuteSql));
workthread.Start();
}
private void ExecuteSql()
{
using (DbConnection connection = new SqlConnection(connectionString))
using (DbCommand command = new SqlCommand())
{
connection.Open();
command.Connection = connection;
command.CommandText = commandText;
command.ExecuteNonQuery();
connection.Close();
}
Console.WriteLine("Execute '{0}' completed", commandText);
}
public void Join()
{
if (workthread != null)
if (workthread.IsAlive) workthread.Join();
}
}
static void Main(string[] args)
{
string connectionString = "你自己的连接串";
SqlExecutor[] executors = new SqlExecutor[]{
new SqlExecutor("Select 1", connectionString),
new SqlExecutor("Select @@version", connectionString)
};
foreach (SqlExecutor executor in executors)
{
executor.DoExecute();
}
foreach (SqlExecutor executor in executors)
{
executor.Join();
}
Console.ReadLine();
}
异常自己捕获
谢谢您的指导。
Thread workthread = new Thread(new ThreadStart(this.ExecuteSql));
workthread.Start();
感谢!
就是这样开辟线程,执行SQL语句就是了。