在我的示例中,我尝试使用多个线程搜索数据库中的数字。我动态地创建线程,但在我的代码中它看起来只有最后一个线程工作是否有任何错误,我创建线程或数据库连接?
exp:我的数据库中有6条记录:
2,3,5,7,11,13
db.threadCount()= 2(它为db记录动态变化)
taskCount [temp] = 3(你可以认为它的一半是db)
for (int i = 0; i < db.threadCount(); i++)
{
int temp = i;
threadEnds+= taskCount[temp];
thereads[i] = new Thread(() => db.searchh(threadBegins,threadEnds, number, temp));
thereads[i].Start();
threadBegins+= taskCount[temp];
}
我的搜索功能:
public void searchh(int starting, int ending, int sitem,int id)
{
int rturn=0;
SqlConnection conn = new SqlConnection("Data Source=DESKTOP-G08P8S7\\SQLEXPRESS;Initial Catalog=numbers;Integrated Security=True");
string command = "SELECT * FROM mytable";
SqlCommand db_command = new SqlCommand(command, conn);
SqlDataAdapter dAdaptor = new SqlDataAdapter();
DataSet dSet = new DataSet();
DataTable dTable = new DataTable();
dAdaptor.SelectCommand = db_command;
conn.Open();
dAdaptor.Fill(dSet);
conn.Close();
dTable = dSet.Tables[0];
for (int i = starting; i <ending; i++)
{
Console.Write(dTable.Rows[i][0] + "value" + id + "th thread\n\n");
if (sitem == ((int)dTable.Rows[i][0]))
{
MessageBox.Show("Test");
}
//Thread.Sleep(1000);
}
}
我的输出:
7值第0个线程
11value 0th thread
13value 0th thread