gpt4 book ai didi

.net - Entity Framework 是否支持并行异步查询?

转载 作者:行者123 更新时间:2023-12-03 06:03:03 24 4
gpt4 key购买 nike

当我们启动多个异步 Entity Framework 查询并并行运行它们时会发生什么?

它们在物理上是并行执行的吗?它们是由 Entity Framework 序列化的吗?这是不支持的吗?会导致异常吗?

public async Task QueryDatabase()
{
using (var context = new MyDbContext())
{
Task task1 = context.SomeTable1.ToListAsync();
Task task2 = context.SomeTable2.ToListAsync();

await Task.WhenAll(task1, task2);
}
}

最佳答案

根据 specifications of version 6 不支持此功能.

这应该抛出一个DbConcurrencyException异常,说

A second operation started on this context before a previousasynchronous operation completed. Use 'await' to ensure that anyasynchronous operations have completed before calling another methodon this context. Any instance members are not guaranteed to be threadsafe.

EF will detect if the developer attempts to execute two async operations at one time and throw.

来自a codeplex page of the project :

Enabling asynchronous execution of database operations is actuallyorthogonal to enabling concurrent execution on the same context. Inthe particular case of server scenarios, using concurrent access couldaffect scalability negatively as it would mean that in order toprocess a single request you would be spinning of an arbitrary numberof different threads. All the threads would compete for resources suchas memory with other threads necessary to server other concurrentrequests.

Entity Framework 核心 does not support this scenario either .

EF Core doesn't 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. This is typically done by using the await keyword on each async operation.

关于.net - Entity Framework 是否支持并行异步查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com