日期:2014-05-17 浏览次数:20574 次
using System; using System.Data; using System.Data.SqlClient; using System.Threading; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { for (int i = 1; i <= 10; i++) { Response.Write("start:" + i.ToString()); new Thread(new ThreadStart(MyThread)).Start(); } for (int i = 1; i <= 10; i++) { Response.Write("start:" + i.ToString()); new Thread(new ThreadStart(TestThread)).Start(); } } private static string connectstring = @"Data Source=127.0.0.1;Initial Catalog=XXXXXX;Persist Security Info=True;User ID=sa;Password=sa"; private static SqlConnection con; /// <summary> /// 取得连接 /// </summary> public static SqlConnection Connection { get { if (con == null) { con = new SqlConnection(connectstring); con.Open(); } else if (con.State == ConnectionState.Broken) { con.Close(); con.Open(); } else if (con.State == ConnectionState.Closed) { con.Open(); } return con; } } static void MyThread() { try { var sql = "SELECT * FROM table1"; SqlCommand cmd = new SqlCommand(sql, Connection); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["mc"].ToString()); } reader.Close(); } catch (Exception ex) { } } static void TestThread() { var sql = "SELECT * FROM table1"; using (SqlConnection myconn = new SqlConnection(connectstring)) { myconn.Open(); SqlCommand cmd =new SqlCommand(sql,myconn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["mc"].ToString()); } reader.Close(); } } }
------解决方案--------------------
缺点:
1.使用static,也就是全局能使用,如果有多线程,那么大家都来争这个资源,建议你可以在控制台中模拟多线程来测试一下,特别是两个线程几乎差不多时间进入此代码获取connection,你可以看看会怎样。
2.把connectstring放在代