How to make OleDb code run asynchronous?

♀尐吖头ヾ 提交于 2019-12-10 10:25:19

问题


I've seen a lot of examples for asynchronous when trying to do Web downloading/reading. But I fail to find a sample or anything for OleDb (or is there a better equivalent?), I'd like to use the new and simplified Async and Await features of C# 5.0.

This is just an example of how I use OleDb now:

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); }
}

I do run a few data readers after each other, multiple times on request, and it's taking quite a while before the new results are showing on the Form. Also, I'm using OleDb to access a Access database.


回答1:


A simple approach would be to wrap the DB operations in a 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";
         }));
    });
}

As mentioned in the comments, if this method is invoked from the UI, you can simply do your async operations in the Task, and when await resumes, there is no need to look for a Dispatcher, since await in this case is resuming on the UI thread. An example of that is given here:

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..
}


来源:https://stackoverflow.com/questions/20849979/how-to-make-oledb-code-run-asynchronous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!