[英]Why await for async method in the middle of a method?
我在书中使用异步/等待的东西找到了这个例子。 请问有人告诉我,等待下例所示的异步方法有什么好处?
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT * FROM People", connection);
await connection.OpenAsync();
SqlDataReader dataReader = **await** command.ExecuteReaderAsync();
while (**await** dataReader.ReadAsync())
{
string formatStringWithMiddleName = "Person ({0}) is named {1} {2} {3}";
string formatStringWithoutMiddleName = "Person ({0}) is named {1} {3}";
if ((dataReader["middlename"] == null))
{
Console.WriteLine(formatStringWithoutMiddleName,
dataReader["id"],
dataReader["firstname"],
dataReader["lastname"]);
}
else
{
Console.WriteLine(formatStringWithMiddleName,
dataReader["id"],
dataReader["firstname"],
dataReader["middlename"],
dataReader["lastname"]);
}
}
dataReader.Close();
}
}
我只是无法解决这个问题。 我的理解是,等待阻塞直到调用的方法(在这种情况下为ExecuteReaderAsync和ReadAsync)返回为止。 调用async方法并立即在代码中间进行阻塞的目的是什么,而实际上在对async方法的调用与将结果返回给调用者的那一点之间实际上没有做任何事情? 比单纯这样做更快或更有效吗?
....
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
.....
我的理解是,等待阻塞直到调用的方法(在这种情况下为ExecuteReaderAsync和ReadAsync)返回为止。
没有; await
将暂停该方法并返回到调用方。 因此,它在ReadAsync
操作期间不会阻塞调用线程。
从概念上讲,这是sync和serial之间的区别。 同步意味着阻塞:方法调用将停止线程,直到Read
完成。 串行一次一次表示:该方法将暂停执行,直到ReadAsync
完成。 因此,常见的await *Async()
模式是串行的,但是是以异步的方式,而不是同步的方式。
有关async
和await
更多信息,请参阅我的async
介绍文章。
这会暂时阻止您的方法,但会使UI线程保持响应。 C#在内部重写该方法。 await
之后的部分将转换为一种回调方法(不是真的,但是可以想象得到)。 该方法立即在await
返回,并在异步操作完成时从上次中断的地方继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.