一:前言
二:多线程查询数据库记录实例
一:前言
. 我们假设数据库里有500条记录,每条记录比作一个金条,那就是有500个金条,一个线程比作一个人,一个人取一个金条放置到自己的筐子里往返一次需要花费掉1分钟,那么取完全部的金条且放置在自己的筐子里共需要花费掉500分钟,那么此时有50个人,还是每个人取一个金条放置到自己的筐子里往返一次需要花费掉1分钟,那么此时50个人一起去取金条,那么取完全部的金条且放置在自己筐子里共需要10分钟
. 多个线程运作一个任务
二:多线程查询数据库记录实例
ThreadSelectDatabase.aspx.cs
namespace EPG.WebAdmin.Test
{
public partial class ThreadSelectDatabase : System.Web.UI.Page
{
private TimeSpan _timeSpent;
public static DataSet _ds;
public TimeSpan timeSpent
{
get { return _timeSpent; }
}
public DataSet DSResult
{
get { return _ds; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 多线程读取
/// </summary>
/// <returns></returns>
public bool MoreThreadSelectRecord()
{
DateTime started = DateTime.Now;//当前的起始时间
Thread[] thread = new Thread[3];//声明线程的个数
WebSite website;
for (int i = 0; i < 3; i++)
{
website = new WebSite();
thread[i] = new Thread(new ThreadStart(website.SearchRecord));
thread[i].Start();
}
for (int i = 0; i < 3; i++)
{
thread[i].Join();//每一个线程都执行完了后,主线程返回
}
_timeSpent = DateTime.Now.Subtract(started);
return true;
}
/// <summary>
/// 单线程读取
/// </summary>
/// <returns></returns>
public bool SingleThreadSearchWebSites()
{
DateTime started = DateTime.Now;//当前的起始时间
WebSite website;
website = new WebSite();
website.SearchRecord();
_timeSpent = DateTime.Now.Subtract(started);
return true;
}
/// <summary>
/// 单线程读取按钮被单击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnOneThread_Click(object sender, EventArgs e)
{
if (SingleThreadSearchWebSites())
{
lblInfo.Text = "找到" + DSResult.Tables[0].Rows.Count + "条记录";
lblInfo.Text += "共花费时间: <font color=\"red\">" + timeSpent + "</font>";
Repeater1.DataSource = DSResult.Tables[0];
Repeater1.DataBind();
}
}
/// <summary>
/// 多线程读取按钮被单击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnMoreThread_Click(object sender, EventArgs e)
{
if (MoreThreadSelectRecord())
{
lblInfo.Text = "找到" + DSResult.Tables[0].Rows.Count + "条记录";
lblInfo.Text += "共花费时间: <font color=\"red\">" + timeSpent + "</font>";
Repeater1.DataSource = DSResult.Tables[0];
Repeater1.DataBind();
}
}
}
class WebSite
{
public WebSite()
{
}
public void SearchRecord()
{
SqlConnection conn = null;
SqlDataAdapter da = null;
conn = SqlHelper.GetConnection();
string strSQL = "SELECT TOP 5000 CategoryName,CategoryDescription,AddTime FROM CategoryInfo WHERE TypeFlag = 0";
da = new SqlDataAdapter(strSQL, conn);
ThreadSelectDatabase._ds = new DataSet();
da.Fill(ThreadSelectDatabase._ds);
}
}
单击“单线程读取按钮”,花费了32秒
单击“多线程读取按钮”,花费了093秒