How to make OleDb code run asynchronous?

醉酒当歌 提交于 2019-12-06 03:07:00

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