[英]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.