小弟我刚开始学线程,现在已到了点麻烦,希望路过的大侠能帮帮忙,最好能给出改进后的解决办法,小弟我感激不尽!
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;
using System.Threading;
namespace 线程练习
{
    public partial class Form1 : Form
    {
        private Thread th;
        //public static bool CheckForIllegalCrossThreadCalls = false;
        public Form1()
        {
            InitializeComponent();
        }
        int x = 10, y = 100;
        public void go()
        {
            while (true)
            {
                x += 10;
                y += 10;
                Thread.Sleep(1000);
               // Refresh();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            th = new Thread(new ThreadStart(go));
            th.Start();
        }        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.FillRectangle(Brushes.Red, x, y, 10, 10);
        }
    }
}

解决方案 »

  1.   

    需要调用控件的 Invoke/BegindInvoke方法,注册一个异步回调,在这个异步回调回调才能去更新控件。执行Invoke/BegineInvoke的当前线程本身是不能更新控件的。
      

  2.   

    你的go方法就不是在主线程,所以要想调用主线程操作,那个操作代码大致应这样写Form1.Invoke(delegate()
      {
        ......;
      });
      

  3.   

    去看吧 最简单的方法就是在构造函数中添加一行代码即可
    CheckForIllegalCrossThreadCalls = false;但是不推荐这么做 具体是为什么以及怎么做 请看链接
    http://hi.baidu.com/yyq745201/blog/item/0156034b3a6b342e08f7ef36.html