C# 如何使OleDb代码异步运行?
在尝试进行Web下载/阅读时,我看到了许多异步的示例。 但是我找不到OleDb的样本或任何东西(或者有更好的等价物吗?),我想使用C#5.0的新的简化异步和等待功能 这只是我现在如何使用OleDb的一个示例:C# 如何使OleDb代码异步运行?,c#,asynchronous,oledb,async-await,oledbdatareader,C#,Asynchronous,Oledb,Async Await,Oledbdatareader,在尝试进行Web下载/阅读时,我看到了许多异步的示例。 但是我找不到OleDb的样本或任何东西(或者有更好的等价物吗?),我想使用C#5.0的新的简化异步和等待功能 这只是我现在如何使用OleDb的一个示例: public void insertTafelloc(int tafelnr, string datum, string tijd) { tafelsupdate = false; try { db.cmd.Connection = db.connection; db.co
public void insertTafelloc(int tafelnr, string datum, string tijd)
{
tafelsupdate = false;
try
{
db.cmd.Connection = db.connection;
db.connection.Open();
db.cmd.CommandText = "SELECT * FROM tafels WHERE tafelnr = ? AND datum = ?";
db.cmd.Parameters.Add(new OleDbParameter("1", tafelnr));
db.cmd.Parameters.Add(new OleDbParameter("2", datum));
OleDbDataReader dataReader;
dataReader = db.cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dataReader.Read())
{
if (dataReader["tafelnr"].ToString() != "")
{
tafelsupdate = true;
}
}
dataReader.Close();
db.cmd.Parameters.Clear();
db.connection.Close();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
我确实会根据请求多次运行一些数据读取器,在新结果显示在表单上之前需要花费相当长的时间。
另外,我正在使用OleDb访问access数据库。一种简单的方法是将DB操作包装到任务中:
public async Task DoDbOperationsAsync()
{
await Task.Run(async () =>
{
// Your DB operations goes here
// Any work on the UI should go on the UI thread
// WPF
await Application.Current.Dispatcher.InvokeAsync(() => {
// UI updates
});
// WinForms
// To do work on the UI thread we need to call invoke on a control
// created on the UI thread..
// "this" is the Form instance
this.Invoke(new Action(() =>
{
button1.Text = "Done";
}));
});
}
如注释中所述,如果从UI调用此方法,您只需在任务中执行异步操作,并且当await
恢复时,无需寻找调度程序,因为在这种情况下,await
正在UI线程上恢复。这里给出了一个例子:
public async void OnButtonClick_DoDbOperationsAsync()
{
await Task.Run(() =>
{
// Your DB operations goes here
});
// You are now back at the UI thread and can update the UI..
}
不嵌套异步调用;只需将该代码放在
wait Task.Run()
调用之后。@SLaks感谢您的提醒-您能否详细说明嵌套异步调用在这里和/或一般情况下不是最佳方法的原因?当从UI线程调用时,wait
将在UI线程上的异步操作后恢复代码。这是全部要点的一部分。谢谢你快速而清晰的回答。但是我对“Application.Current.Dispatcher”部分有一个问题,我不明白为什么.Current不存在?我在Form1.cs中以及在我的单独类中使用oledb代码尝试了这些代码。错误为:“System.Windows.Forms.Application”不包含“Current”的定义@Arndroid我现在更新了答案以涵盖WinForms和WPF:)