更新Datagrid datacontext会占用内存

时间:2013-08-07 15:12:35

标签: c# wpf memory-leaks

我有一个WPF数据网格,我需要每分钟更新一次。我添加了一个DispatchTimer来获取数据并更新datagrid的数据Context。问题是数据似乎正在四处徘徊。首先我认为这是我的列表,但我只是运行了更新的我的dataContext列表,我没有看到使用内存的megs。

        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

我将它设置为1秒进行测试。

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        ObservableCollection<Technician> techData = LoadData();
        DG1.DataContext = null;
        DG1.DataContext = techData;
    }

...

    private ObservableCollection<Technician> LoadData()
    {
        ObservableCollection<Technician> techData = new ObservableCollection<Technician>();

        Uri uriGreenImage = new Uri("pack://application:,,,/Images/green.png");
        Uri uriRedImage = new Uri("pack://application:,,,/Images/red.png");

        // Connect to Database.
        Database db = new Database();

        string query = "SELECT * FROM dbo.StatusBoard ORDER BY dbo.StatusBoard.LastName";

        SqlDataReader reader = db.Query(query);

        while (reader.Read())
        {
            BitmapImage statusImage;

            switch(reader["Status"].ToString())
            {
                case "0":
                    statusImage = new BitmapImage(uriGreenImage);
                    break;
                case "1":
                    statusImage = new BitmapImage(uriRedImage);
                    break;
                default:
                    statusImage = new BitmapImage(uriRedImage);
                    break;
            }

            techData.Add(new Technician
            {
                FullName = reader["FirstName"].ToString() + " " + reader["LastName"].ToString(),
                Comments = reader["Comments"].ToString(),
                Status = statusImage,
                WatchingServiceDesk = (reader["WatchingServiceDesk"].ToString() == "1" ? true : false),
                Phone = reader["Phone"].ToString()
            });
        }

        return techData;
    }

0 个答案:

没有答案