c# - 在c#中使用async和await时UI将被阻塞

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

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

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

另外,我需要一些说明

1)await keyword is using to wait some time until the process is completed, then what is the difference b/w synchronous and asynchronous process.

2)If one method is declared as Async task, then all inner methods are performing as asynchronous?

3)While Executing inner methods(method1,method2,method3), method3 will be depends upon method1. So, put await keyword for method1. Am I right?

代码片段:

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

最佳答案

1) await keyword is using for wait some time until the process is completed, then what is the difference b/w synchronous and asynchronous process.

同步:WAITING会阻塞线程,因此锁定 ui
异步:WAITING会释放线程,因此不会阻塞 ui

2) If one method is declared as Async task, then all inner methods are performing as asynchronous?

不要认为这是真的。您可能希望情况如此,但这取决于您作为开发人员是否以这种方式编码。
编译器不会为您强制执行此操作。

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

3) While Executing inner methods(method1,method2,method3), method3 will be depends upon method1. So, put await keyword for method1. Am i right?

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

关于c# - 在c#中使用async和await时UI将被阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47454699/

相关文章:

c# - 多线程sqldatareader时间过期

c# - 如何触发 WPF 上下文菜单的关闭动画?

c# - 如何将 CheckBox 添加到 TemplateField HEADER?

c# - WPF 中的异步任务

c# - Async/Await 如何处理 "old"结果?

c# - 为什么这段使用 yield return 的代码可以编译?

c# - 异步上传和调整多个图像时出现内存不足异常

javascript - 使用异步等待时无法获取对象的属性

c# - BeginReceive 回调中的异步/等待

c# - 如何拆分和合并此数据流管道?