非同步儲存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 核心不支援在相同的內容執行個體上執行的多個平行作業。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();
    }
}