非同步查詢Asynchronous Queries

非同步查詢避免封鎖執行緒,而資料庫中執行查詢。Asynchronous queries avoid blocking a thread while the query is executed in the database. 這可避免凍結大型用戶端應用程式的 UI。This can be useful to avoid freezing the UI of a thick-client application. 非同步作業,也可以增加 web 應用程式,其中執行緒可以釋放資料庫作業完成時服務的其他要求中的輸送量。Asynchronous operations can also increase throughput in a web application, where the thread can be freed up to service other requests while the database operation completes. 如需詳細資訊,請參閱在 C# 中的非同步程式設計For more information, see Asynchronous Programming in C#.

警告

EF 核心不支援在相同的內容執行個體上執行的多個平行作業。EF Core does not support multiple parallel operations being run on the same context instance. 您應該永遠等候作業完成,然後再開始下一項作業。You should always wait for an operation to complete before beginning the next operation. 這通常是使用await上每個非同步作業的關鍵字。This is typically done by using the await keyword on each asynchronous operation.

Entity Framework Core 提供一組可用來當做替代造成查詢執行的 LINQ 方法並傳回結果的非同步擴充方法。Entity Framework Core provides a set of asynchronous extension methods that can be used as an alternative to the LINQ methods that cause a query to be executed and results returned. 範例包括ToListAsync()ToArrayAsync()SingleAsync()等等。沒有 LINQ 運算子的非同步版本例如Where(...)OrderBy(...)等因為這些方法僅建置 LINQ 運算式樹狀架構,而不會造成查詢執行在資料庫中。Examples include ToListAsync(), ToArrayAsync(), SingleAsync(), etc. There are not async versions of LINQ operators such as Where(...), OrderBy(...), etc. because these methods only build up the LINQ expression tree and do not cause the query to be executed in the database.

重要

EF 核心非同步擴充方法中定義Microsoft.EntityFrameworkCore命名空間。The EF Core async extension methods are defined in the Microsoft.EntityFrameworkCore namespace. 此命名空間必須匯入可用的方法。This namespace must be imported for the methods to be available.

public async Task<List<Blog>> GetBlogsAsync()
{
    using (var context = new BloggingContext())
    {
        return await context.Blogs.ToListAsync();
    }
}