最佳答案
我有一个 MVC 网站,使用实体框架6来处理数据库,我一直在尝试改变它,使一切运行作为异步控制器和数据库的调用运行作为它们的异步对应(例如,。ToListAsync ()而不是 ToList ())
我遇到的问题是,仅仅将查询更改为异步就会导致它们变得异常缓慢。
下面的代码从我的数据上下文中获取“ Album”对象的集合,并转换为一个相当简单的数据库连接:
// Get the albums
var albums = await this.context.Albums
.Where(x => x.Artist.ID == artist.ID)
.ToListAsync();
下面是创建的 SQL:
exec sp_executesql N'SELECT
[Extent1].[ID] AS [ID],
[Extent1].[URL] AS [URL],
[Extent1].[ASIN] AS [ASIN],
[Extent1].[Title] AS [Title],
[Extent1].[ReleaseDate] AS [ReleaseDate],
[Extent1].[AccurateDay] AS [AccurateDay],
[Extent1].[AccurateMonth] AS [AccurateMonth],
[Extent1].[Type] AS [Type],
[Extent1].[Tracks] AS [Tracks],
[Extent1].[MainCredits] AS [MainCredits],
[Extent1].[SupportingCredits] AS [SupportingCredits],
[Extent1].[Description] AS [Description],
[Extent1].[Image] AS [Image],
[Extent1].[HasImage] AS [HasImage],
[Extent1].[Created] AS [Created],
[Extent1].[Artist_ID] AS [Artist_ID]
FROM [dbo].[Albums] AS [Extent1]
WHERE [Extent1].[Artist_ID] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=134
随着事情的发展,这并不是一个非常复杂的查询,但是 SQL 服务器运行它需要将近6秒钟。SQLServer 事件探查器报告需要5742ms 才能完成。
如果我将代码更改为:
// Get the albums
var albums = this.context.Albums
.Where(x => x.Artist.ID == artist.ID)
.ToList();
然后生成完全相同的 SQL,但根据 SQLServer 事件探查器,这只需要474毫秒。
该数据库在“ Albums”表中有大约3500行,这并不是很多,并且在“ Artist _ ID”列上有一个索引,所以应该非常快。
我知道异步有一定的开销,但是让事情慢上十倍对我来说似乎有点过分!我到底哪里做错了?