我试图从MS访问数据库读取行并在屏幕上显示它时,当每个显示器之间有几秒钟的睡眠时间。
我正在使用System.Threading
,但是看来睡眠在程序显示记录之前发生,而睡眠结束时只显示最后一个记录,而没有显示上一个记录。
这是我的代码,我将非常感谢任何帮助!
private void com_start_Click(object sender, EventArgs e)
{
try
{
string ConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:MyBrainWashEnglishdb.accdb;";
OleDbConnection Con = new OleDbConnection(ConString);
Con.Open();
check_connection.Text = "succeeded";
OleDbCommand command = new OleDbCommand();
command.Connection = Con;
command.CommandText = "Select * From words";
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
Thread.Sleep(30000);
}
}
reader.Close();
Con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
UI控制lab_word
和lab_definition.Text
将在整个com_start_Click
方法完成后进行更新。
这就是为什么您看到只显示最后一排的原因。
您需要"释放" UI线程阅读每行3秒钟以更新新值UI控件。
我认为async/await
方法非常适合此目的。
用async
关键字单击标记按钮。
private async void com_start_Click(object sender, EventArgs e)
{
string ConString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:MyBrainWashEnglishdb.accdb;";
using (var Con = new OleDbConnection(ConString))
{
Con.Open();
check_connection.Text = "successed";
using (var command = new OleDbCommand())
{
command.Connection = Con;
command.CommandText = "Select * From words";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
await Task.Delay(30000);
}
}
}
}
}
您还可以使用OleDbConnection
,OleDbCommand
和OleDbReader
private async void com_start_Click(object sender, EventArgs e)
{
string ConString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:MyBrainWashEnglishdb.accdb;";
using (var Con = new OleDbConnection(ConString))
{
await Con.OpenAsync();
check_connection.Text = "successed";
using (var command = new OleDbCommand())
{
command.Connection = Con;
command.CommandText = "Select * From words";
using (var reader = await command.ExecuteReader())
{
while (await reader.ReadAsync())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
await Task.Delay(30000);
}
}
}
}
}