C# timer 时间长会占用很大内存

早起晚睡 2016-01-07 08:02:27
加精
timer1_Tick 事件里面我不管有没有代码 只要timer启动以后我的执行程序占用的内存就会一直增加 时间一长就会当机
不知道大神门有没有解决办法!!!!
...全文
9935 42 打赏 收藏 转发到动态 举报
写回复
用AI写文章
42 条回复
切换为时间正序
请发表友善的回复…
发表回复
早起晚睡 2016-01-15
  • 打赏
  • 举报
回复
在主要代码前后加上 该程序使用内存的情况就能及时发现那个地方内存占用比较大!!! 能够提高效率!!!!!!
早起晚睡 2016-01-15
  • 打赏
  • 举报
回复
                        for (int j = 2; j <= 50; j++)
                        {
                            if (!(j == 24 || j == 48 || j == 33))
                            {
                                for (int i = 2; i <= 254; i++)
                                {
                                    using (Ping myPing = new Ping())
                                    {  //Ping myPing;
                                       // myPing = new Ping();
                                        myPing.PingCompleted += new PingCompletedEventHandler(myPing_PingCompleted);

                                        string pingIP = "192.168." + j.ToString() + "." + i.ToString();
                                        myPing.SendAsync(pingIP, 1000, null);
                                       // myPing = null;
                                      //  pingIP = null;
                                    }
                                }
                            }

                            //Application.DoEvents();
                        }
这里面的Ping myPing = new Ping()不释放 加using解决 通过查看本程序使用内存情况就能定位哪里的代码占用内存比较多从而进行优化
private void press()
        {
            //新建一个Stopwatch变量用来统计程序运行时间
            // Stopwatch watch = Stopwatch.StartNew();
             //获取本机运行的所有进程ID和进程名,并输出哥进程所使用的工作集和私有工作集
             foreach (Process ps in Process.GetProcesses())
             {
                 PerformanceCounter pf1 = new PerformanceCounter("Process", "Working Set - Private", ps.ProcessName);
                 PerformanceCounter pf2 = new PerformanceCounter("Process", "Working Set", ps.ProcessName);
                 if (ps.ProcessName == "PcIpAddress")
                 {
                     listBox1.Items.Add(ps.ProcessName + "工作集(进程类)" + (ps.WorkingSet64 / 1024).ToString());
                     listBox1.Items.Add(ps.ProcessName + "工作集" + (pf2.NextValue() / 1024).ToString());
                     listBox1.Items.Add(ps.ProcessName + "工作集" + (pf1.NextValue() / 1024).ToString());
                 }
                 
 
             }

            // watch.Stop();
            // Console.WriteLine(watch.Elapsed);


        }
秋的红果实 2016-01-14
  • 打赏
  • 举报
回复
贴出源码看看 理论上将,没有执行代码,不会导致这样的结果
dubuyunjie 2016-01-14
  • 打赏
  • 举报
回复
就问你是winform还是wpf
dubuyunjie 2016-01-14
  • 打赏
  • 举报
回复
引用 35 楼 dubuyunjie 的回复:
就问你是winform还是wpf
wpf看看这个 http://www.cnblogs.com/Nikola/p/4635455.html
早起晚睡 2016-01-14
  • 打赏
  • 举报
回复
using能释放吗????
早起晚睡 2016-01-14
  • 打赏
  • 举报
回复
你还是在循环里面呢啊
_小黑_ 2016-01-14
  • 打赏
  • 举报
回复
应该 不是timer 的问题 是你 对象没释放 导致的吧
早起晚睡 2016-01-14
  • 打赏
  • 举报
回复
找到内存增长的问题所在了!
xiaoxiangqing 2016-01-14
  • 打赏
  • 举报
回复
应该不会吧,没有执行耗时的代码,不应该。
wish907 2016-01-14
  • 打赏
  • 举报
回复
while (reader.Read()) //label1.Text = "name:" + reader["name"].ToString(); //数据读取 { kk = "YG" + reader["pcygid"].ToString() + "," + reader["pcuser"].ToString() + "," + reader["pcremark"].ToString() + "," + reader["deptName"].ToString() + "," + reader["pcaddress"].ToString() + "," + reader["pcmacadd"] + "," + str; if (!File.Exists(strdt + "PCTxt.txt")) { using (FileStream fs1 = new FileStream(strdt + "PCTxt.txt", FileMode.Create, FileAccess.Write)) {//创建写入文件 using (StreamWriter sw = new StreamWriter(fs1)) { sw.WriteLine(kk + "," + DateTime.Now);//开始写入值 sw.Flush(); } } } else { using (FileStream fs = new FileStream(strdt + "PCTxt.txt", FileMode.Append)) { using (StreamWriter sr = new StreamWriter(fs)) { sr.WriteLine(kk + "," + DateTime.Now);//开始写入值 sr.Flush(); } } } } 光是文件修改你就可以放在while外面 中间只用一个变量记录一下 数据库同理
纯粹码农 2016-01-14
  • 打赏
  • 举报
回复
看看hehe
早起晚睡 2016-01-13
  • 打赏
  • 举报
回复
引用 27 楼 Tidal_Choidi 的回复:
撸主,不是Timer定时器本身对内存的消耗过大,而是定时器里面处理的事务比较复杂或者你的定时器里面处理的代码性能问题导致的系统内存开销过大。
我知道 关键是怎么解决啊!!!!!
lts981 2016-01-13
  • 打赏
  • 举报
回复
不懂哦。。。
Tidal_Choidi 2016-01-13
  • 打赏
  • 举报
回复
撸主,不是Timer定时器本身对内存的消耗过大,而是定时器里面处理的事务比较复杂或者你的定时器里面处理的代码性能问题导致的系统内存开销过大。
早起晚睡 2016-01-13
  • 打赏
  • 举报
回复
引用 25 楼 xdashewan 的回复:
[quote=引用 24 楼 bjgzxx 的回复:] 加个bool变量有什么用 希望给个解释
既然上代码了,那我来告诉你这篇程序的明显问题。首先你的timer的启动停止逻辑可以优化,可以考虑用System.Threading.Timer延迟触发,避免反复开关timer,当然这是小事并不是重点。你这代码最大缺陷就是数据库连接操作和文件开关操作实在太频繁,其原因就是把这两操作全都放在循环里执行,极大地消耗了资源。垃圾回收机制不是你想象那么简单,就算你执行了回收代码,其实也不是一定马上就回收的。其他不用改,把数据库连接和文件开闭都放到各自循环外去运行,应该就没问题了[/quote]有道理 在循环里 操作太频繁了!!!
事理 2016-01-12
  • 打赏
  • 举报
回复
试试吧


 bool complete = true;
        bool complete2 = true;
        private void timer1_Tick(object sender, EventArgs e)
        {

            ts = TimeSpan.Parse(DateTime.Now.ToString("HH:mm:ss"));

            if (!string.IsNullOrEmpty(comboBox1.Text ))
            {
                if (ts > TimeSpan.Parse(comboBox1.Text + ":00:00") && ts < TimeSpan.Parse(comboBox1.Text + ":00:03"))
                {
                    if (complete == true)
                    {
                        complete = false;
                        listBoxAddrs.Items.Clear();
                        kg = true;
                        try
                        {
                            Ping myPing;
                            myPing = new Ping();
                            myPing.PingCompleted += new PingCompletedEventHandler(myPing_PingCompleted);
                            for (int j = 2; j <= 50; j++)
                            {
                                if (!(j == 24 || j == 48 || j == 33))
                                {
                                    for (int i = 2; i <= 254; i++)
                                    {
                                        string pingIP = "192.168." + j.ToString() + "." + i.ToString();
                                        myPing.SendAsync(pingIP, 1000, null);
                                    }
                                }
                                myPing = null;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        complete = true;
                    }
                }
            }
            //if (kg)
            //{
            //    System.Threading.Thread.Sleep(4000);
            //}
            //DateTime dt = DateTime.Parse(textBox1.Text);
            //if (DateTime.Now>=dt && )
            //{
            //    MessageBox.Show("ddd");
            //}

            // string selectStr1 = "select pc.pcmacadd,pc.pcremark,pc.pcaddress,pc.pcuser,pc.pcygid,dept.deptName from  pc,dept where pc.deptID=dept.deptID and pc.pcip not in (SELECT pcIP  FROM pc where pcAddress like '%磅%' or pcAddress like '%监控%' or pcAddress like '%开票%' or pcAddress like '%门%' or pcAddress like '%库%' or pcAddress like '%调度%' or pcAddress like '%主控%' or pcAddress like '%取样%') and pcremark<>'路由器' and pcremark<>'倒班' and pcremark<>'值班24小时' and pc.pcIP='";

            if (kg)
            {
                if (listBoxAddrs.Items.Count > 0 && complete2 = true)
                {
                    complete2 = false;
                    selectStr = string.Empty;
                    kk = string.Empty;
                    //IPbutton.Enabled = false;
                    //databt.Enabled = false;
                    //label1.Text = "不要关闭程序正在做数据操作";
                    string strdt = DateTime.Now.ToString("yyyyMMddHHmm");
                    using (SqlConnection connection = new SqlConnection(strConn))
                    {
                        command.Connection.Open();
                        foreach (string str in listBoxAddrs.Items)
                        {
                            selectStr = selectStr1 + str.Substring(8, str.Length - 8) + "'";

                            try
                            {
                                SqlCommand command = new SqlCommand(selectStr, connection);
                                using (SqlDataReader reader = command.ExecuteReader())
                                {
                                    while (reader.Read())
                                    //label1.Text = "name:" + reader["name"].ToString();    //数据读取
                                    {
                                        kk = "YG" + reader["pcygid"].ToString() + "," + reader["pcuser"].ToString() + "," + reader["pcremark"].ToString() + "," + reader["deptName"].ToString() + "," + reader["pcaddress"].ToString() + "," + reader["pcmacadd"] + "," + str;
                                        if (!File.Exists(strdt + "PCTxt.txt"))
                                        {
                                            using (FileStream fs1 = new FileStream(strdt + "PCTxt.txt", FileMode.Create, FileAccess.Write))
                                            {//创建写入文件 
                                                using (StreamWriter sw = new StreamWriter(fs1))
                                                {
                                                    sw.WriteLine(kk + "," + DateTime.Now);//开始写入值
                                                    sw.Flush();
                                                }
                                            }
                                        }
                                        else
                                        {
                                            using (FileStream fs = new FileStream(strdt + "PCTxt.txt", FileMode.Append))
                                            {
                                                using (StreamWriter sr = new StreamWriter(fs))
                                                {
                                                    sr.WriteLine(kk + "," + DateTime.Now);//开始写入值
                                                    sr.Flush();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (SqlException ex)
                            {
                                throw ex;
                            }
                        }
                    }
                    //IPbutton.Enabled = true;
                    //databt.Enabled = true;
                    //label1.Text = "查询操作完毕请找PCtxt文件";
                    complete2 = true;
                    listBoxAddrs.Items.Clear();
                    kg = false;
                    num = 0;
                }
                else
                {
                    lbIPs.Text = "没有查到在线的电脑";
                }
                recordTime = DateTime.Now.Subtract(startTime);
                if (recordTime.Seconds % 3 == 0)
                {
                    //3秒中手动回收一次内存
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }

        }
早起晚睡 2016-01-12
  • 打赏
  • 举报
回复
跑一段时间会稳定 只是一天内稳定 ,时间一长 就会弄死电脑了!!!!! 不知道出再哪里了 真是愁人啊
        private void myPing_PingCompleted(object sender, PingCompletedEventArgs e)
        {
            //StringBuilder sb = new StringBuilder();

            if (e.Reply.Status == IPStatus.Success)
            {
                if (e.Reply.Address.ToString().Trim() != "")
                {
                    this.listBoxAddrs.Items.Add(e.Reply.Address.ToString());
                    //string mac = GetMacAddress(e.Reply.Address.ToString());
                    //sb.Append(" " + mac );
                    num++;
                }

            }

            //this.txtAddrs.Text += sb.ToString();  

            this.lbIPs.Text = "在线IP数:" + num.ToString();

        }
xdashewan 2016-01-12
  • 打赏
  • 举报
回复
引用 24 楼 bjgzxx 的回复:
加个bool变量有什么用 希望给个解释
既然上代码了,那我来告诉你这篇程序的明显问题。首先你的timer的启动停止逻辑可以优化,可以考虑用System.Threading.Timer延迟触发,避免反复开关timer,当然这是小事并不是重点。你这代码最大缺陷就是数据库连接操作和文件开关操作实在太频繁,其原因就是把这两操作全都放在循环里执行,极大地消耗了资源。垃圾回收机制不是你想象那么简单,就算你执行了回收代码,其实也不是一定马上就回收的。其他不用改,把数据库连接和文件开闭都放到各自循环外去运行,应该就没问题了
早起晚睡 2016-01-12
  • 打赏
  • 举报
回复
引用 23 楼 slyzly 的回复:
试试吧


 bool complete = true;
        bool complete2 = true;
        private void timer1_Tick(object sender, EventArgs e)
        {

            ts = TimeSpan.Parse(DateTime.Now.ToString("HH:mm:ss"));

            if (!string.IsNullOrEmpty(comboBox1.Text ))
            {
                if (ts > TimeSpan.Parse(comboBox1.Text + ":00:00") && ts < TimeSpan.Parse(comboBox1.Text + ":00:03"))
                {
                    if (complete == true)
                    {
                        complete = false;
                        listBoxAddrs.Items.Clear();
                        kg = true;
                        try
                        {
                            Ping myPing;
                            myPing = new Ping();
                            myPing.PingCompleted += new PingCompletedEventHandler(myPing_PingCompleted);
                            for (int j = 2; j <= 50; j++)
                            {
                                if (!(j == 24 || j == 48 || j == 33))
                                {
                                    for (int i = 2; i <= 254; i++)
                                    {
                                        string pingIP = "192.168." + j.ToString() + "." + i.ToString();
                                        myPing.SendAsync(pingIP, 1000, null);
                                    }
                                }
                                myPing = null;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        complete = true;
                    }
                }
            }
            //if (kg)
            //{
            //    System.Threading.Thread.Sleep(4000);
            //}
            //DateTime dt = DateTime.Parse(textBox1.Text);
            //if (DateTime.Now>=dt && )
            //{
            //    MessageBox.Show("ddd");
            //}

            // string selectStr1 = "select pc.pcmacadd,pc.pcremark,pc.pcaddress,pc.pcuser,pc.pcygid,dept.deptName from  pc,dept where pc.deptID=dept.deptID and pc.pcip not in (SELECT pcIP  FROM pc where pcAddress like '%磅%' or pcAddress like '%监控%' or pcAddress like '%开票%' or pcAddress like '%门%' or pcAddress like '%库%' or pcAddress like '%调度%' or pcAddress like '%主控%' or pcAddress like '%取样%') and pcremark<>'路由器' and pcremark<>'倒班' and pcremark<>'值班24小时' and pc.pcIP='";

            if (kg)
            {
                if (listBoxAddrs.Items.Count > 0 && complete2 = true)
                {
                    complete2 = false;
                    selectStr = string.Empty;
                    kk = string.Empty;
                    //IPbutton.Enabled = false;
                    //databt.Enabled = false;
                    //label1.Text = "不要关闭程序正在做数据操作";
                    string strdt = DateTime.Now.ToString("yyyyMMddHHmm");
                    using (SqlConnection connection = new SqlConnection(strConn))
                    {
                        command.Connection.Open();
                        foreach (string str in listBoxAddrs.Items)
                        {
                            selectStr = selectStr1 + str.Substring(8, str.Length - 8) + "'";

                            try
                            {
                                SqlCommand command = new SqlCommand(selectStr, connection);
                                using (SqlDataReader reader = command.ExecuteReader())
                                {
                                    while (reader.Read())
                                    //label1.Text = "name:" + reader["name"].ToString();    //数据读取
                                    {
                                        kk = "YG" + reader["pcygid"].ToString() + "," + reader["pcuser"].ToString() + "," + reader["pcremark"].ToString() + "," + reader["deptName"].ToString() + "," + reader["pcaddress"].ToString() + "," + reader["pcmacadd"] + "," + str;
                                        if (!File.Exists(strdt + "PCTxt.txt"))
                                        {
                                            using (FileStream fs1 = new FileStream(strdt + "PCTxt.txt", FileMode.Create, FileAccess.Write))
                                            {//创建写入文件 
                                                using (StreamWriter sw = new StreamWriter(fs1))
                                                {
                                                    sw.WriteLine(kk + "," + DateTime.Now);//开始写入值
                                                    sw.Flush();
                                                }
                                            }
                                        }
                                        else
                                        {
                                            using (FileStream fs = new FileStream(strdt + "PCTxt.txt", FileMode.Append))
                                            {
                                                using (StreamWriter sr = new StreamWriter(fs))
                                                {
                                                    sr.WriteLine(kk + "," + DateTime.Now);//开始写入值
                                                    sr.Flush();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (SqlException ex)
                            {
                                throw ex;
                            }
                        }
                    }
                    //IPbutton.Enabled = true;
                    //databt.Enabled = true;
                    //label1.Text = "查询操作完毕请找PCtxt文件";
                    complete2 = true;
                    listBoxAddrs.Items.Clear();
                    kg = false;
                    num = 0;
                }
                else
                {
                    lbIPs.Text = "没有查到在线的电脑";
                }
                recordTime = DateTime.Now.Subtract(startTime);
                if (recordTime.Seconds % 3 == 0)
                {
                    //3秒中手动回收一次内存
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }

        }
加个bool变量有什么用 希望给个解释
加载更多回复(20)

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧