非同步儲存Asynchronous Saving

非同步儲存可避免在將變更寫入至資料庫時阻斷執行緒。Asynchronous saving avoids blocking a thread while the changes are written to 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 Core 不支援在同一個內容執行個體上執行多個平行作業。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 提供 DbContext.SaveChangesAsync() 作為 DbContext.SaveChanges()的替代方案。Entity Framework Core provides DbContext.SaveChangesAsync() as an asynchronous alternative to DbContext.SaveChanges().

public static async Task AddBlogAsync(string url)
{
    using (var context = new BloggingContext())
    {
        var blog = new Blog { Url = url };
        context.Blogs.Add(blog);
        await context.SaveChangesAsync();
    }
}