dotMemory和追踪内存泄漏

3
我有一个基本的Web应用程序MVC,EF6。用户有一个仪表板,显示包含来自两个不同数据库系统的数据的表格。 MSSQL和Informix(使用IBM.Data.Informix)。
随着时间的推移,IIS进程会不断消耗内存。我使用dotMemory来帮助我定位它,但现在正在尝试弄清楚如何读取这些数据。
我保持网页打开状态,并且每10秒钟就会有一个Ajax调用返回新数据。
第四个快照是在第三个快照几个小时后拍摄的。 enter image description here 总数与下面的数字不匹配,但某些地方不对。
下面的图片似乎告诉我,我的应用程序最多只使用10mb。 enter image description here 我还在查看堆,但似乎这不是大块的地方。 enter image description here enter image description here enter image description here 我仍在查找视频和指南,以帮助我找到此问题的位置。我正在使用许多内置框架,我真的看不出我使用的代码有什么问题,除非存在某个错误或我确实错过了不应该在代码中执行的某些操作。
数据库管理器
public class DatabaseManager : IDisposable
{
    private bool disposed = false;
    private SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);

    private PatientCheckinEntities db { get; set; }

    private IfxConnection conn { get; set; }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public DatabaseManager()
    {
        string ifxString = System.Configuration.ConfigurationManager.ConnectionStrings["ifx"].ConnectionString;
        conn = new IfxConnection(ifxString);
        db = new PatientCheckinEntities();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            handle.Dispose();

            IfxClose();
            conn.Dispose();
            db.Dispose();
        }

        disposed = true;
    }

    private void IfxClose()
    {
        if (conn.State == System.Data.ConnectionState.Open)
        {
            conn.Close();
        }
    }

    private void IfxOpen()
    {
        if (conn.State == System.Data.ConnectionState.Closed)
        {
            conn.Open();
        }
    }

    public ProviderModel GetProviderByResourceID(string id)
    {
        ProviderModel provider = new ProviderModel();

        using (IfxDataAdapter ida = new IfxDataAdapter())
        {
            ida.SelectCommand = new IfxCommand("SELECT description FROM sch_resource WHERE resource_id = ? FOR READ ONLY", conn);
            IfxParameter ifp1 = new IfxParameter("resource_id", IfxType.Char, 4);
            ifp1.Value = id;
            ida.SelectCommand.Parameters.Add(ifp1);

            IfxOpen();
            object obj = ida.SelectCommand.ExecuteScalar();
            IfxClose();
            if (obj != null)
            {
                string name = obj.ToString();

                provider.ResourceID = id.ToString();
                string[] split = name.Split(',');

                if (split.Count() >= 2)
                {
                    provider.LastName = split[0].Trim();
                    provider.FirstName = split[1].Trim();
                }
                else
                {
                    provider.LastName = name.Trim();
                }

                ProviderPreference pp = db.ProviderPreferences.Where(x => x.ProviderID.Equals(id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                int globalWait = Convert.ToInt32(GetConfigurationValue(ConfigurationSetting.WaitThreshold));

                if (pp != null)
                {
                    provider.Preferences.DisplayName = pp.DisplayName;
                    provider.Preferences.WaitThreshold = pp.WaitThreshold.HasValue ? pp.WaitThreshold.Value : globalWait;
                }
                else
                {
                    provider.Preferences.WaitThreshold = globalWait;
                }
            }
        }

        return provider;
    }

    public List<PatientModel> GetCheckedInPatients(List<string> providers)
    {
        List<PatientModel> patients = new List<PatientModel>();

        foreach (string provider in providers)
        {
            List<PatientModel> pats = db.PatientAppointments
                        .Where(x => provider.Contains(x.ProviderResourceID)
                        && DbFunctions.TruncateTime(x.SelfCheckInDateTime) == DbFunctions.TruncateTime(DateTime.Now))
                            .Select(x => new PatientModel()
                            {
                                Appointment = new AppointmentModel()
                                {
                                    ID = x.AppointmentID,
                                    DateTime = x.AppointmentDateTime,
                                    ArrivalTime = x.ExternalArrivedDateTime
                                },
                                FirstName = x.FirstName,
                                LastName = x.LastName,
                                SelfCheckIn = x.SelfCheckInDateTime,
                                Provider = new ProviderModel()
                                {
                                    ResourceID = x.ProviderResourceID
                                }
                            }).ToList();

            patients.AddRange(pats.Select(x => { x.Provider = GetProviderByResourceID(x.Provider.ResourceID); return x; }));
        }

        using (IfxDataAdapter ida = new IfxDataAdapter())
        {
            ida.SelectCommand = new IfxCommand("SELECT arrival_time::char(5) as arrival_time FROM sch_app_slot WHERE appointment_key = ? FOR READ ONLY", conn);

            IfxOpen();
            foreach (PatientModel patient in patients)
            {
                ida.SelectCommand.Parameters.Clear();
                IfxParameter ifx1 = new IfxParameter("appointment_key", IfxType.Serial);
                ifx1.Value = patient.Appointment.ID;
                ida.SelectCommand.Parameters.Add(ifx1);

                using (IfxDataReader dr = ida.SelectCommand.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        if (dr.HasRows)
                        {
                            string arrival = dr["arrival_time"].ToString();

                            if (!string.IsNullOrWhiteSpace(arrival) && !patient.Appointment.ArrivalTime.HasValue)
                            {
                                PatientAppointment pa = new PatientAppointment();
                                pa.AppointmentID = patient.Appointment.ID;
                                pa.AppointmentDateTime = patient.Appointment.DateTime;
                                pa.FirstName = patient.FirstName;
                                pa.LastName = patient.LastName;

                                string dt = string.Format("{0} {1}", patient.Appointment.DateTime.ToString("yyyy-MM-dd"), arrival);
                                pa.ExternalArrivedDateTime = DateTime.ParseExact(dt, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
                                patient.Appointment.ArrivalTime = pa.ExternalArrivedDateTime;
                                pa.ProviderResourceID = patient.Provider.ResourceID;
                                pa.SelfCheckInDateTime = patient.SelfCheckIn;

                                db.PatientAppointments.Attach(pa);
                                db.Entry(pa).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            IfxClose();
        }


        patients = patients.Select(x => { x.Appointment.WaitedMinutes = (int)Math.Round(((TimeSpan)x.Appointment.ArrivalTime.Value.Trim(TimeSpan.TicksPerMinute).Subtract(x.SelfCheckIn.Trim(TimeSpan.TicksPerMinute))).TotalMinutes); return x; }).ToList();

        List<PatientModel> sorted = patients.Where(x => !x.Appointment.ArrivalTime.HasValue).OrderBy(x => x.SelfCheckIn).ThenBy(x => x.Provider.ResourceID).ToList();
        sorted.AddRange(patients.Where(x => x.Appointment.ArrivalTime.HasValue).OrderBy(x => x.Appointment.DateTime).ThenBy(x => x.Provider.ResourceID));

        return sorted;
    }

    private string GetConfigurationValue(string id)
    {
        return db.Configurations.Where(x => x.ID.Equals(id)).Select(x => x.Value).FirstOrDefault();
    }
}

控制器

[HttpPost]
[Authorize]
public ActionResult GetCheckedIn(List<string> provider)
{
    DashboardViewModel vm = new DashboardViewModel();
    try
    {
        if (provider.Count > 0)
        {
            using (DatabaseManager db = new DatabaseManager())
            {
                vm.Patients = db.GetCheckedInPatients(provider);
            }
        }
    }
    catch (Exception ex)
    {
        //todo
    }
    return PartialView("~/Views/Dashboard/_InnerTable.cshtml", vm);
}
2个回答

2

我看到你正在使用System.xml.Schema...根据版本不同,每个实例会创建大约80K的非托管内存泄漏。因此,每使用12次,您在非托管内存中就有1MB的内存泄漏。 如果可能的话,请尝试缓存而不是每次创建新的实例。


2

您的应用程序消耗了大量的本地内存,而不是.NET内存。查看.NET内存消耗,它约为12Mb,并且不会密集增长。看起来您没有在某些使用本地内存的对象上调用Dispose方法,例如数据库连接对象或类似对象。检查此类对象的数量,如果您没有释放它们,该数字将不断增长。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接