FindAsync缓慢,但延迟加载速度很快 [英] FindAsync is Slow, but lazy loading is fast

查看:146
本文介绍了FindAsync缓慢,但延迟加载速度很快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我曾经使用 await FindAsync 加载相关实体,希望我更好地符合c#异步指南。

  var activeTemplate = await exec.DbContext 
.FormTemplates.FindAsync(exec.Form.ActiveTemplateId);

它运行缓慢,在sql server profiler中缓慢,SSMS中的查询文本很快。取得这一行花了5秒钟。



替代方案:

  var activeTemplate = exec.Form.ActiveTemplate; 

要快得多
一般来说,这个问题似乎并不是参数嗅探,因为快速和慢速查询中的读取次数是相同的。



不相关的一点是,获取的对象包含一个包含〜1MB文本的字符串属性。应用程序是asp.net mvc,与sql server在同一台计算机上运行,​​连接使用(本地)。



观察到的缓慢的原因是什么? p>

编辑:在@ jbl的评论之后,我做了一些更多的实验:

  var activeTemplate = await exec.DbContext.FormTemplates 
.FirstOrDefaultAsync(x => x.Id == exec.Form.ActiveTemplateId); // slow

var activeTemplate = exec.DbContext.FormTemplates
.FirstOrDefault(x => x.Id == exec.Form.ActiveTemplateId); // fast


解决方案

Async方法在阅读时可能会出现性能问题来自服务器的大列(如varbinary(MAX),varchar(MAX),nvarchar(MAX)或XML))。



您可以找到rducom 答案解释异步方法的问题此处


In my code, I used to load a related entity using await FindAsync, hoping that i better conform to c# async guidelines.

var activeTemplate = await exec.DbContext
.FormTemplates.FindAsync(exec.Form.ActiveTemplateId);

and it ran slow, was slow in sql server profiler, the query text was fast in SSMS. It took 5 seconds to fetch this line.

The alternative:

var activeTemplate = exec.Form.ActiveTemplate;

is much faster. By all means, the problem does not seem to be parameter sniffing, as the number of reads in the fast and slow queries are the same.

One possibly irrelevant point is that the fetched object contains a string property containing ~1MB text. The application is asp.net mvc, running on the same computer as the sql server, connecting using (local).

What is the cause of the observed slowness?

EDIT: After @jbl's comment, I did some more experiments:

var activeTemplate = await exec.DbContext.FormTemplates
.FirstOrDefaultAsync(x => x.Id == exec.Form.ActiveTemplateId); // slow

var activeTemplate = exec.DbContext.FormTemplates
.FirstOrDefault(x => x.Id == exec.Form.ActiveTemplateId); // fast

解决方案

Async method can have performance issue when reading a large column from the server (such as varbinary(MAX), varchar(MAX), nvarchar(MAX) or XML).

You can find rducom answer which explain the issue with async method here

这篇关于FindAsync缓慢,但延迟加载速度很快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆