【问题标题】:UI will be blocked while using async and await in c#在 c# 中使用 async 和 await 时 UI 将被阻止
【发布时间】:2017-11-23 11:41:44
【问题描述】:

这里我需要将一些数据从本地服务器导出到 Excel。我正在使用async 调用该方法。但是,它仍然在导出数据时阻塞了 UI。

我可以知道 UI 被阻塞的原因吗?

另外,我需要澄清一下

1)await 关键字用于等待一段时间,直到进程完成 完成,那么 b/w 同步和 异步进程。

2)如果一个方法被声明为Async任务,那么所有的内部方法 以异步方式执行?

3)在执行内部方法(method1,method2,method3)时,method3会 取决于方法1。所以,把await关键字放在method1上。我是不是 对吧?

代码sn-p:

private async void ConvertExcel(object sender)
{
    var excelEngine = new ExcelEngine();
    var application = excelEngine.Excel;
    var newbookWorkbook = application.Workbooks.Create(1);
    var work = newbookWorkbook.Worksheets[0];
    var openDialog = new SaveFileDialog
    {
        FilterIndex = 2,
        Filter = "Excel 97 to 2003 Files(*.xls)|*.xls|Excel 2007 to 2013 Files(*.xlsx)|*.xlsx"
    };
    if (openDialog.ShowDialog() == true)
    {
        newbookWorkbook.Version = openDialog.FilterIndex == 1 ? ExcelVersion.Excel97to2003 : ExcelVersion.Excel2013;
    }
    else
        return;
    try
    {            
         // This method is used to get the data from server.          
         var table =  GetFullDataAsync();
         work.ImportDataTable(table, true, 1, 1, true);
         using (Stream stream = openDialog.OpenFile())
         {
            newbookWorkbook.SaveAs(stream);
         }

         newbookWorkbook.Close();
         excelEngine.Dispose();
    }
    catch (Exception exception)
    {
       Console.WriteLine("Exception message: {0}",ex.Message);
    }
}

internal async Task<DataTable> GetFullDataAsync()
{
    DataTable dataTable = new DataTable();
    dataTable = GetDataFromServer(DataEngine.Query,DataEngine.Connection);

    dataTable.Locale = CultureInfo.InvariantCulture;
    return dataTable;
}        


public DataTable GetDataFromServer(string query, DbConnection connection)
{
    if (connection.State != ConnectionState.Open)
    {
        connection.Open();
    }

    var command = connection.CreateCommand();
    command.CommandText = query; 
    command.Connection = connection;

    var reader = command.ExecuteReader();
    var dataTable = new DataTable
    {
        Locale = System.Globalization.CultureInfo.InvariantCulture
    };
    dataTable.Load(reader);
    return dataTable;
}

【问题讨论】:

  • 您的async 方法对await 没有任何作用。同样来自async 方法的返回类型应该是Task。
  • 你的方法根本不是异步的,因为它实际上并没有做任何与任务或类似的事情。只需添加async 并不会神奇地使其异步,您还需要使用await 和任务。

标签: c# asynchronous async-await task ui-thread


【解决方案1】:

1) await 关键字是使用 for 等待一段时间,直到进程完成,那么黑白同步和异步进程有什么区别。

同步:等待阻塞线程,因此锁定 ui
异步:等待释放线程,所以不会阻塞用户界面

2) 如果一个方法被声明为异步任务,那么所有内部方法都是异步执行的?

不要以为这是真的。您可能希望这样,但作为开发人员,您可以采用这种方式编写代码。
编译器不会为您强制执行此操作。

在您上面的代码中,答案是否定的;您的代码不是异步的。请注意,您从不使用 await 关键字。
您可能需要先以异步方式访问数据(返回任务),否则 async/await 关键字无法帮助您。

3) 在执行内部方法(method1,method2,method3) 时,method3 将依赖于method1。因此,为方法 1 放置 await 关键字。我说的对吗?

是的。如果每个方法都返回一个任务,则等待它们。 通常,当您在一个地方开始使用 await 时,它会在您的其余代码中冒泡,因此您可以按照您的描述继续添加更多的 await。

【讨论】:

  • 如果我放 await 它将等待完成该操作。所以它会像同步一样。那么等待之前和等待之后有什么区别?
  • 在您的具体情况下,没有区别。 await 仅适用于已经异步的代码。它不会神奇地使您的数据库调用从同步更改为异步。您要查找异步 DB 调用(例如command.ExecuteReaderAsync())
  • 表达感谢的最佳方式是点赞和/或接受答案
【解决方案2】:

你试过了吗

GetFullDataAsync().ContinueWith((table)=>{
      work.ImportDataTable(table, true, 1, 1, true);
         using (Stream stream = openDialog.OpenFile())
         {
            newbookWorkbook.SaveAs(stream);
         }

         newbookWorkbook.Close();
         excelEngine.Dispose();
})

【讨论】:

  • 嗨@lzikon,我也试试这个。出现同样的问题。
【解决方案3】:

您可以更改代码以使用与 Sql 服务器的异步通信,如下所示:

private async Task ConvertExcel(object sender)
{
    var excelEngine = new ExcelEngine();
    var application = excelEngine.Excel;
    var newbookWorkbook = application.Workbooks.Create(1);
    var work = newbookWorkbook.Worksheets[0];
    var openDialog = new SaveFileDialog
    {
        FilterIndex = 2,
        Filter = "Excel 97 to 2003 Files(*.xls)|*.xls|Excel 2007 to 2013 Files(*.xlsx)|*.xlsx"
    };
    if (openDialog.ShowDialog() == true)
    {
        newbookWorkbook.Version = openDialog.FilterIndex == 1 ? ExcelVersion.Excel97to2003 : ExcelVersion.Excel2013;
    }
    else
        return;
    try
    {            
         // This method is used to get the data from server.          
         var table = await GetFullDataAsync();
         work.ImportDataTable(table, true, 1, 1, true);

         var saveWorkbookTask = Task.Run(() => {
             using (Stream stream = openDialog.OpenFile())
             {
                newbookWorkbook.SaveAs(stream);
             }
         });

         await saveWorkbookTask;

         newbookWorkbook.Close();
         excelEngine.Dispose();
    }
    catch (Exception exception)
    {
       Console.WriteLine("Exception message: {0}",ex.Message);
    }
}

internal async Task<DataTable> GetFullDataAsync()
{
    DataTable dataTable = new DataTable();
    dataTable = await GetDataFromServer(DataEngine.Query,DataEngine.Connection);

    dataTable.Locale = CultureInfo.InvariantCulture;
    return dataTable;
}        


public async Task<DataTable> GetDataFromServer(string query, DbConnection connection)
{
    if (connection.State != ConnectionState.Open)
    {
        connection.Open();
    }

    var command = connection.CreateCommand();
    command.CommandText = query; 
    command.Connection = connection;

    var reader = await command.ExecuteReaderAsync();

    var loadTableTask = Task.Run(() => {
        var dataTable = new DataTable
        {
            Locale = System.Globalization.CultureInfo.InvariantCulture
        };
        dataTable.Load(reader);
        return dataTable;
    });

    return await loadTableTask;
}

但是您仍然有阻塞的 IO 操作。因此,如果您的文件大于将文件写入磁盘时 UI 将被阻止。

【讨论】:

  • 嗨@michael,我在sql server 中有超过50,000,000 条记录。是阻塞UI的原因吗?
  • 您的初始代码在运行 SQL 查询并将文件写入磁盘时阻塞了执行线程。我已经使 SQL 服务器操作异步,但是将数据加载到 DataTable 并将新文件写入磁盘仍然同步运行。您可以在单独的线程中运行此操作,以防止您的 UI 冻结。
  • 检查Task.Run 允许从线程创建任务的方法。
  • 但 UI 将被冻结,然后执行以下行,将数据加载到 DataTable 并将新文件写入磁盘。
  • 你有什么样的应用程序?它是 WinForms 桌面应用程序吗?
猜你喜欢
  • 2016-02-08
  • 2016-10-06
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
相关资源
最近更新 更多