如何让OleDb代码运行异步?

Arn*_*oid 3 c# oledb asynchronous oledbdatareader async-await

我在尝试进行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); }
}
Run Code Online (Sandbox Code Playgroud)

我会根据请求多次运行一些数据读取器,并且在表单上显示新结果之前需要花费很长时间.此外,我正在使用OleDb访问Access数据库.

Las*_*sen 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";
         }));
    });
}
Run Code Online (Sandbox Code Playgroud)

正如评论中所提到的,如果从UI调用此方法,您只需在Task中执行异步操作,并且在await恢复时,不需要查找Dispatcher,因为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..
}
Run Code Online (Sandbox Code Playgroud)

  • 当从UI线程调用时,`await`将在UI线程上的异步操作之后恢复代码.这是整点的一部分. (2认同)