Asp .Net Core 2.1 遇到的内存泄露

 这个问题遇到是几个月以前了,一个老的用.net core mvc写的升到.net core 2.1.6的时候发现内存泄漏,经过排查是因为闭包的问题导致的。

出现问题的代码类似如下:

 

 public class XXXXXController : ControllerBase
    {
        protected XXXXContext context;
         public ActionResult MatchList()
        {
            var matchs = context.Matches.Include(y => y.MatchBanner).OrderByDescending(x=>x.EndTime);
            var recommends = context.Recommends.Include(y => y.Match);
            return new JsonResult(matchs.Select(x => new
            {
                id = x.ID,
                x.Title,
                startTime = x.StartTime.ToString("yyyy-MM-dd"),
                endTime = x.EndTime.ToString("yyyy-MM-dd"),
                x.NeedVIP,
                x.MatchDetail,
                x.Price,
                banner =x.MatchBanner.URL==null?GetImageUrl(x.MatchBanner.ID): x.MatchBanner.URL,  //this line have a problem
            }));
        }
        public string GetImageUrl(int? imageID)
        {
            return $"api/GuessWhat/ImageShow/{imageID}";
        }
    }

将其中的:

 banner =x.MatchBanner.URL==null?GetImageUrl(x.MatchBanner.ID): x.MatchBanner.URL,

改为:

 banner =x.MatchBanner.URL==null? $"api/GuessWhat/ImageShow/{x.MatchBanner.ID}" : x.MatchBanner.URL,  

问题解决。

问题原因如下:

https://github.com/aspnet/EntityFrameworkCore/issues/14099

The issue here is, in order to perform client eval requested by user, we capture the closure. But closure also contains the DbContext hence memory is leaked. Easy work-around for now would be to use static method which wouldn't capture the instance of repository

简单来说就是:新版本的.net core 为了提升性能对访问做了缓存,这样一个闭包导致了DbContext的泄露,将引用的方法改为static就好咯~~。

 

 

 

 

 

你可能感兴趣的:(asp.net,MVC,学习)