如何正确使用aysnc / await与UI和数据库访问 [英] How to correctly use aysnc/await with UI and database access

查看:93
本文介绍了如何正确使用aysnc / await与UI和数据库访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在VS 2015中使用async并等待关键字时,是否可以帮助我弄清楚为什么我的初始UI测试消息无法正确显示?

我的代码如下:



Can someone help me figure out why my initial UI test message is not displaying correctly when I use async and await keywords in VS 2015?
My code follows here:

private async Task<datatable> ExecuteSQLASync(SQLiteConnection conn, string sqlStmnt)
{
   SQLiteDataAdapter da = new SQLiteDataAdapter(sqlStmnt, conn);
   DataSet ds = new DataSet();
   da.Fill(ds);

   Thread.Sleep(2000); // only to slow things down for testing.

   return ds.Tables[0];
}

async private void StartExecuteSQLAsync(SQLiteConnection conn, string sqlStmnt)
{
   try
   {
      txtMsg.Text = "Starting SQL Query in Background: " + sqlStmnt;
      txtMsg.ForeColor = Color.Blue;

      DataTable dt = await ExecuteSQLASync(conn, sqlStmnt);

      dataGridViewSQLQuery.DataSource = dt;
      lblNumRowsText.Text = m_SQLQueryDataTable.Rows.Count.ToString();

      txtMsg.Text = "Results for SQL query:" + sqlStmnt;
      txtMsg.ForeColor = Color.Green;
   }
   catch (Exception ex)
   {
      txtMsg.Text = ex.Message;
      txtMsg.ForeColor = Color.Red;
   }
}





问题是,我从未看到我的第一条消息为蓝色 - 我看不到任何消息直到ExecuteSQLASync方法完成之后,我才看到绿色的最终消息。我错过了什么?



谢谢。



我尝试了什么:



我尝试使用async / await关键字来创建非阻塞的异步数据库访问,但我必须误解正确的用法。



The problem is, I never see my first message in blue - I see no message at all until after the ExecuteSQLASync method has completed and then I see the final message in green. What am I missing?

Thanks.

What I have tried:

I have tried using the async/await keywords to create a non-blocking asynchronous database access but I must have misunderstood the correct usage.

推荐答案

你正在使用async / await关键字,但你似乎没有启动在后台运行的新线程,我会尝试一下:



you are using the async / await keywords but you don't seem to start a new thread that runs in the background, I would give this a try:

private DataTable ExecuteSQLASync(SQLiteConnection conn, string sqlStmnt)
{
  // ...
}

DataTable dt =  await Task.Run(   () => ExecuteSQLASync(conn, sqlStmnt)   );


这篇关于如何正确使用aysnc / await与UI和数据库访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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