源代码如下    public partial class Form1 : Form
    {
        public static bool started;
        public static int result;        public Form1()
        {
            InitializeComponent();
        }        private void SButton_Click(object sender, EventArgs e)
        {
            started = true;
            Selectit sel = new Selectit();
            Thread selthread = new Thread(sel.Startselect);
            selthread.Start();
            while (selthread.IsAlive)
            {
                selthread.Suspend();
                numlable.Text = result.ToString();
                this.Refresh();
                selthread.Resume();
                if (!started) { selthread.Abort(); }
            }
        }        private void Stop_Click(object sender, EventArgs e)
        {
            started = false;
        }
        public class Selectit
        {
            public void Startselect()
            {
                while (Form1.started)
                {
                    Random ran = new Random();
                    result = ran.Next(1, 126);
                    Thread.Sleep(100);
                }
            }
        }
    }
用于学校抽签的一个小程序,不知为何UI在点击开始按钮后就死了,一开始通过使用This.Refresh()让Lable可以刷新,但是停止按钮还是不能使用。BTW,Suspend和Resume两个函数VS一直说不推荐使用,是由于这个导致的么?多线程ui

解决方案 »

  1.   

    是因为你在线程中访问UI控件,换用backgroudworker实现吧
      
    *****************************************************************************
    签名档: http://feiyun0112.cnblogs.com/
      

  2.   

    没必要用线程的,不就是每100ms出个随机数么,100ms定时器就好了。
      

  3.   

    this.Refresh();=>Application.DoEvents();
    换成  DoEvents试试。。
      

  4.   


     public partial class Form1 : Form
        {
            public static bool started;
            public static int result;        public Form1()
            {
                InitializeComponent();
            }        private void SButton_Click(object sender, EventArgs e)
            {
                started = true;
                Selectit sel = new Selectit();
                Thread selthread = new Thread(sel.Startselect);
                selthread.Start();
                if (!started) { selthread.Abort(); }
            }        private void Stop_Click(object sender, EventArgs e)
            {
                started = false;
            }
            public class Selectit
            {
                public void Startselect()
                {
                    while (Form1.started)
                    {
                        Random ran = new Random();
                        Application.OpenForms[0].Invoke(new MethodInvoker(delegate
                            {
                                Form1.numlable.Text = ran.Next(1, 126).ToString();
                            }));
                        Thread.Sleep(100);
                    }
                }
            }
        }再把numlable改成静态的,因为你又写了个类,这样访问方便点。还有selthread 最好定义成全局的,不用每次都实例化