窗口里面的timer执行较消耗时间的操作,我又不想用线程,如何避免窗口被锁住,这个应该是个常见问题啊,为什么没人回答呢,我的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;
namespace ProcessControl
{
    public partial class Form1 : Form
    {
        private delegate void SetTextDelegate();
        private System.DateTime dt=System.DateTime.Now;
        public Form1()
        {
            InitializeComponent();
        }
        void pro()
        {
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
            string[] strlist = ConfigurationSettings.AppSettings["exepath"].Split(new char[] { ',' });
            foreach (string str in strlist)
            {
                Thread.Sleep(10);
                bool find = false;
                foreach (System.Diagnostics.Process myProcess in myProcesses)
                {
                    Thread.Sleep(10);
                    try
                    {
                        if (str == myProcess.MainModule.FileName)
                        {
                            find = true;
                        }
                    }
                    catch
                    {
                        //MessageBox.Show(ex.Message);
                    }
                    //Application.DoEvents();                }
                if (find == false)
                {
                    System.Diagnostics.Process.Start(str);
                    if (textBox1.Text.Length > 1000) { textBox1.Text = ""; }
                    textBox1.Text = textBox1.Text + "start exe " + str + "\r\n";                    
                }
                
            }
            System.DateTime dn = System.DateTime.Now;            TimeSpan tp = dn.Subtract(dt);
            if (tp.TotalMinutes > int.Parse(ConfigurationSettings.AppSettings["time"]))
            {
                System.Diagnostics.Process[] myProcesses1 = System.Diagnostics.Process.GetProcesses();                foreach (System.Diagnostics.Process myProcess in myProcesses1)
                {
                    string[] strlist1 = ConfigurationSettings.AppSettings["exepath"].Split(new char[] { ',' });
                    foreach (string str in strlist1)
                    {
                        Thread.Sleep(10);
                        try
                        {
                            if (str == myProcess.MainModule.FileName)
                            {
                                myProcess.Kill();
                                if (textBox1.Text.Length > 1000) { textBox1.Text = ""; }
                                textBox1.Text = textBox1.Text + "kill exe " + str + "\r\n";
                            }
                        }
                        catch
                        {                        }                    }
                }
                dt = dn;
                label4.Text = dn.ToString();
             //   Application.DoEvents();
            }
            
            
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            BeginInvoke(new SetTextDelegate(pro));
        }
                private void Form1_Load(object sender, EventArgs e)
        {
            //SetTextDelegate pr= new SetTextDelegate(pro);
        }        private void button1_Click(object sender, EventArgs e)
        {
            label5.Text = ConfigurationSettings.AppSettings["time"];
            timer1.Enabled = true;
        }        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }
    }
}程序的作用就是定时关闭某些程序然后再启动。主要是窗口老是卡死卡死的,郁闷得很

解决方案 »

  1.   

    在Application.DoEvents();后面进行Thread.Sleep(1000);
      

  2.   

    在循环里用Application.DoEvents(); 
    在textBox1.Text更新之后紧接着Application.DoEvents(); 
      

  3.   

    try:   
        
      namespace   MyThread   
      {   
      public   class   TestThread   
      {   
      private   bool   _falg   =   false;   
      private   System.Windows.Forms.Label   label1;   
      private   System.Threading.Thread   timeThread;     
      public   TestThread()   
      {   
      }   
      private   void   RunThread()   
      {   
      //这里开始线程   
      this._flag   =   true;   
      timeThread   =   new   Thread(new   ThreadStart(TestThreadTimer));   
      timeThread.Start();   
      }   
      private   void   StopThread()   
      {   
      this._flag   =   false;   
      if(timeThread.ThreadState   !=   ThreadState.Running)   
      timeThread.Start();   
      timeThread.Abort();   
      }   
      public   void   TestThreadTimer()   
      {   
      while(this._flag)   
      {   
      this.label1.Text   =   DateTime.Now.ToString();   
      System.Threading.Thread.Sleep(500);   
      }   
      }   
      }   
      }   
      
      

  4.   

    问题还是没有得到解决啊,用Application.DoEvents(); 后情况更糟,不仅不能解决卡住界面的问题,甚至timer的处理都被阻塞了,不过把timer的时间间隔改为10000看起来就不卡了,不过这样并没有解决实质的问题,如果用timer来刷新窗口上显示的内容(快速大量的话),窗口还是会卡住,如果各位觉得自己问题可行,可以先写个测试代码,然后贴出来
      

  5.   

    正好写过这样的程序,实现起来并不难,根本不会有卡的情况出现:
        public partial class XtraForm1 : DevExpress.XtraEditors.XtraForm
        {
            System.Timers.Timer timer = new System.Timers.Timer(60000);
            public XtraForm1()
            {
                InitializeComponent();
                simpleButton2.Enabled = false;
                timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            }        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                var seconds = (DateTime.Now.TimeOfDay - ((DateTime)timeEdit1.EditValue).TimeOfDay).TotalSeconds;
                if (seconds >= -30 && seconds < 30)
                {
                    RestartBFAPPS();
                }
            }        private void simpleButton1_Click(object sender, EventArgs e)
            {
                simpleButton1.Enabled = false;
                simpleButton2.Enabled = true;
                timeEdit1.Enabled = false;
                timer.Start();
            }        private void simpleButton2_Click(object sender, EventArgs e)
            {
                simpleButton1.Enabled = true;
                simpleButton2.Enabled = false;
                timeEdit1.Enabled = true;
                timer.Stop();
            }        void RestartBFAPPS()
            {
                //关闭BFAPPS
                Process[] ps = Process.GetProcessesByName("BFAPPS");
                foreach (var p in ps)
                {
                    try
                    {
                        p.Kill();
                        p.WaitForExit();
                    }
                    catch (Exception EX)
                    {
                        File.AppendAllText("error.log", EX.Message);
                    }
                }            Thread.Sleep(1000);
                //开启BFAPPS
                try
                {
                    Process p = new Process();
                    p.StartInfo.WorkingDirectory = @"D:\posdata\bfapp";
                    p.StartInfo.FileName = @"BFAPPS.exe";
                    p.Start();
                }
                catch (Exception EX)
                {
                    File.AppendAllText("error.log", EX.Message);
                }
            }        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
            {
                ShowWindow(this.Handle, 1);
                SetForegroundWindow(this.Handle);
            }        private void XtraForm1_Resize(object sender, EventArgs e)
            {
                if (WindowState == FormWindowState.Minimized)
                {
                    this.Hide();
                }
            }        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
            public static extern bool SetForegroundWindow(IntPtr hWnd);   //WINAPI 设置当前活动窗体的句柄        [DllImport("user32.dll")]
            public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);        [DllImport("user32.dll")]
            public static extern bool FlashWindow(
            IntPtr hWnd,           //   handle   to   window   
            bool bInvert       //   flash   status   
            );
        }
      

  6.   


    当然啦。DoEvents本来就是那种玩意儿,跟线程没法比。
      

  7.   

    currentTimeThread = new Thread(new ThreadStart(CountTime));
                currentTimeThread.IsBackground = true;//设置为后台线程
      

  8.   

    我专门写了下,已经解决了这个问题了,界面刷新的时候,同时还可以做其他窗体操作,完全不影响。using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;namespace AsynCallMethod
    {
        public partial class Form1 : Form
        {
            public delegate void ComplexCallback(object objParams);
            public delegate void AddListItemCallback(string strItemText);
            public delegate void SetLabelTextCallback(string sLabelText);        private bool m_bIsBusy = false;
            private DateTime dtStart;        private ComplexCallback callback = null;        public Form1()
            {
                InitializeComponent();
            }        private void button1_Click(object sender, EventArgs e)
            {
                int iInterval=1000;
                if (int.TryParse(textBox1.Text, out iInterval))
                    timer1.Interval = iInterval;
                timer1.Enabled = true;
            }        private void DoWork(object objParams)
            {
                m_bIsBusy = true;
                dtStart = DateTime.Now;
                callback = new ComplexCallback(DoComplexWork);
                callback.BeginInvoke(objParams, new AsyncCallback(EndDoComplexWork), callback);
            }        private void DoComplexWork(object objParams)
            {
                for (int i = 1; i <10000; i++)
                {
                    AddListItem(i.ToString());
                }
            }        private void EndDoComplexWork(IAsyncResult ar)
            {
                callback = ar.AsyncState as ComplexCallback;
                callback.EndInvoke(ar);
                SetLabelText((new TimeSpan(DateTime.Now.Ticks - dtStart.Ticks)).TotalSeconds.ToString() + "秒");
                m_bIsBusy = false;
            }        private void AddListItem(string sItemText)
            {
                if (listBox1.InvokeRequired)
                {
                    AddListItemCallback callback = new AddListItemCallback(AddListItem);
                    listBox1.Invoke(callback, new object[] { sItemText });
                }
                else
                {
                    listBox1.Items.Add(sItemText);
                }
            }        private void SetLabelText(string sLabelText)
            {
                if (label3.InvokeRequired)
                {
                    SetLabelTextCallback callback = new SetLabelTextCallback(SetLabelText);
                    label3.Invoke(callback, new object[] { sLabelText });
                }
                else
                {
                    label3.Text = sLabelText;
                }
            }        private void timer1_Tick(object sender, EventArgs e)
            {
                object objParams = null;            if (!m_bIsBusy)
                    DoWork(objParams);
            }        private void button2_Click(object sender, EventArgs e)
            {
                timer1.Stop();
                timer1.Enabled = false;
            }
        }
    }
      

  9.   

    把测试程序的窗体设置贴上:
    http://hi.csdn.net/attachment/201001/17/2008458_1263702665rYp1.png
      

  10.   

    yulinlover的代码不错
    qldsrx的也可以实现要求(但是没有实现怎么在线程里或者时间函数里面显示消息到窗体上,这个也是我问的最主要的)
      

  11.   

    yulinlover到另外一个帖子结哈分
    http://topic.csdn.net/u/20100115/21/00edea51-1680-4959-9180-fd53fc97a5d2.html