日期:2014-05-18  浏览次数:20822 次

对线程很不理解。Control.Invoke
C# code
        /// <summary>
        /// 线程。
        /// </summary>
        private Thread myThread;
        public Form1()
        {
            InitializeComponent();
          //  Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("这是主线程");
        }

        private void ThreadTask()
        {
            int stp, newVal;
            Random random = new Random();

            if (this.progressBar1.InvokeRequired)
            {
                mythis m = new mythis(ThreadTask);
                this.progressBar1.Invoke(m);
            }

            while (true)
            {
                stp = this.progressBar1.Step * random.Next(-1, 2);
                newVal = this.progressBar1.Value + stp;
                if (newVal > this.progressBar1.Maximum)
                    newVal = this.progressBar1.Maximum;
                else if (newVal < this.progressBar1.Minimum)
                    newVal = this.progressBar1.Minimum;
                this.progressBar1.Value = newVal;
                Thread.Sleep(100);
            }
        }
        delegate void mythis();
        private void Form1_Load(object sender, EventArgs e)
        {
            myThread = new Thread(new ThreadStart(this.ThreadTask));
            myThread.IsBackground = true;
            myThread.Start();
        }


出来的效果是main线程无限等待,然后进度条在不断跳动。就是除了button1无法按下,其他都达到效果了。请问怎么解决?
// Control.CheckForIllegalCrossThreadCalls = false;
这个方法我懂,可是不好。只是屏蔽错误。初学线程。

------解决方案--------------------
另外说点,下面的代码最好是在判断this.InvokeRequired之后。
 int stp, newVal; 
 Random random = new Random(); 

就是放到else里面。
if (this.InvokeRequired)
{
mythis m = new mythis(ThreadTask);
this.Invoke(m);
}else{
//...
}