c# winform定时刷新

发布时间 2023-05-23 11:21:28作者: qingjiawen

 

Thread多线程

   public partial class Form2 : Form
    {
        //横向滚动条记录的是像素位数
        //竖向滚动条记录的行的索引值
        int VerticalScrollIndex = 0;
        int HorizontalOffset = 0;
        public Form2()
        {
            InitializeComponent();
            searchData();
        }
        /// <summary>
        /// 查找数据(查询调用函数)
        /// </summary>
        private void searchData()
        {
            //开始查询数据
            Thread th = new Thread(new ThreadStart(StartSearchData))
            {  
//设置为后台线程,否则即使主程序界面关闭了,程序也不会真正关闭,子线程会继续执行下去 th.IsBackground = true;
} th.Start(); }
//控制下面while 循环,实现定时刷新的效果,如果在查询开始的时候需要设置为true, //如果不需要定时查询了设置为false就好 bool IsReflash = true; private delegate void InvokeHandler();//使用代理让主线程去处理控件数据 /// <summary> ///开始查询数据库的数据 /// </summary> private void StartSearchData() { try { while (IsReflash) { string sql = string.Format("select * from Student "); SqlCommand cmd = new SqlCommand(sql, DBhelper.conn()); DBhelper.conn().Open(); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(sql, DBhelper.conn()); da.Fill(dt); //判断句柄是否被创建,创建之后才能使用 Invoke及BeginInvoke if (this.IsHandleCreated) { this.Invoke(new InvokeHandler(delegate () { dataGridView1.DataSource = dt; dataGridView1.FirstDisplayedScrollingRowIndex = VerticalScrollIndex; })); } Thread.Sleep(2000);//设置刷新时长 } } catch (Exception ex) { MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void dataGridView1_Scroll(object sender, ScrollEventArgs e) { if (e.ScrollOrientation == ScrollOrientation.VerticalScroll) { VerticalScrollIndex = e.NewValue; } else if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll) { HorizontalOffset = e.NewValue; } } }

 

System.Timers.Timer

private static System.Timers.Timer timer = new System.Timers.Timer();
private static int inTimer = 0;

 private void Form1_Load(object sender, EventArgs e)//初始化
        {
            timer.Interval = 1 * 60 * 1000;//默认每1小时执行一次
                    timer.Enabled = true;
                    timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
                    timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
       
        }

  //定时执行事件
        private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            XmlModel.Config _model = DataOperation.Instance.GetConfig();
            if (_model != null)
            {
                DateTime currentDt = DateTime.Now;
                DateTime time1begin = DateTime.Parse(_model.StartTime);
                DateTime time1end = DateTime.Parse(_model.EndTime);
                //在特定时间内
                if (currentDt > time1begin && currentDt < time1end)
                {
                    //业务逻辑代码
                    if (Interlocked.Exchange(ref inTimer, 1) == 0)
                    {
                        //业务逻辑代码
                        StringBuilder slog = new StringBuilder();
                        slog.AppendFormat("Total memory: {0:###,###,###,##0} bytes", GC.GetTotalMemory(true));
                        WriteLog(slog.ToString());
                        slog.Clear();
                        Interlocked.Exchange(ref inTimer, 0);

                    }
                }
            }



        }
  #region 内存回收
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        /// <summary> 
        /// 释放内存
        /// </summary> 
        public static void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }
        #endregion