如何让OleDb代码运行异步?

时间:2013-12-31 00:44:54

标签: c# asynchronous oledb async-await oledbdatareader

我在尝试进行Web下载/阅读时看到了很多异步的例子。 但我找不到OleDb的样本或任何东西(或者是否有更好的等价物?),我想使用C#5.0的新的和简化的Async和Await功能。

这只是我现在如何使用OleDb的一个例子:

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数据库。

1 个答案:

答案 0 :(得分:5)

一种简单的方法是将DB操作包装在Task:

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恢复时,不需要查找Dispatcher,因为{在这种情况下,{1}}在UI线程上恢复。这里给出了一个例子:

await