dotMemory和跟踪内存泄漏

时间:2017-01-21 22:17:27

标签: c# entity-framework memory-leaks dotmemory

我有我认为的基本Web应用程序MVC,EF6。用户有一个仪表板,其中包含一个包含来自两个不同数据库系统的数据的表。 MSSQL和Informix(使用IBM.Data.Informix)。

随着时间的推移,IIS进程只会继续吃掉ram。我抓住dotMemory来帮助我找到它,但现在试图弄清楚如何读取这些数据。

我打开了网页,每隔10秒就会有一个Ajax调用返回新数据。

第4张快照是在第3张快照后的几个小时拍摄的。 enter image description here

总数与下面的数字不匹配,但事情并非如此。

下面的图片似乎告诉我,我的应用程序最多只能使用10mb。

enter image description here

我还在寻找堆,但看起来这不是大块的地方。

enter image description here enter image description here enter image description here

我还在挖掘视频和指南,以帮助我找出找到这个问题的方法。我使用了很多内置框架,我真的没有看到我使用的代码存在问题,除非某处有错误或者我真的错过了一些我不应该做的事情'在代码中做。

的DatabaseManager

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 个答案:

答案 0 :(得分:1)

您的应用消耗了大量本机内存,而不是.NET内存。看看.NET内存消耗大约是12Mb并且没有密集增长。您似乎没有在使用本机内存的某些对象上调用Dispose方法,例如数据库连接对象或类似的东西。检查一些这样的对象,如果你没有释放它们,这个数字会不断增长。

答案 1 :(得分:1)

我看到您使用的是System.xml.Schema ....,具体取决于版本,这将为大约80K的每个实例创建非托管内存泄漏。因此,每12次使用一次,就会在非托管内存中造成1兆的内存泄漏。 不必每次都创建一个新文件,而是尽可能对其进行缓存。

相关问题