【发布时间】: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