如何使OleDb代码异步运行? [英] How to make OleDb code run asynchronous?

查看:121
本文介绍了如何使OleDb代码异步运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

我确实应要求多次运行多个数据读取器,并且要花很长时间才能将新结果显示在表单上. 另外,我正在使用OleDb访问Access数据库.

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.

推荐答案

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

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

如注释中所述,如果从UI调用此方法,则只需在Task中执行异步操作,并且当await恢复时,就无需查找Dispatcher,因为await在这种情况下,将在UI线程上恢复.此处提供了一个示例:

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

这篇关于如何使OleDb代码异步运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆