C#多线程示例(摇号)

using System;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Form1.CheckForIllegalCrossThreadCalls = false;
            /*
             * 在多线程程序中,新创建的线程不能访问UI线程创建的窗口控件,
               这个时候如果你想要访问窗口的控件,那么你可以将窗口构造函数
               中的CheckForIllegalCrossThreadCalls设置为false.这是线程就
               能安全的访问窗体控件了.
             */
        }

        Thread[] _thread = new Thread[3];
        Boolean _bool = false;
        private void Form1_Load(object sender, EventArgs e)
        {
            _thread[0] = new Thread(new ThreadStart(delegate { Run(textBox1); }));
            _thread[1] = new Thread(new ThreadStart(delegate { Run(textBox2); }));
            _thread[2] = new Thread(new ThreadStart(delegate { Run(textBox3); }));
        }

        Random ran = new Random();//随机数
        public void Run(TextBox tb)
        {
            /*
             * 在程序中,常常有一些无限循环的情况,比如当一个程序没有异常发生的时候,
             * 让循环一直执行。比如要计算PI的值,当发生异常的时候终止循环,这时候就需要while(true) ... break 着种结构。
             * 这不是新语法,也不算新用法。算得上一种不常见的能解决特殊问题的用法。
                */
            while (true)
            {
                tb.Text = ran.Next(0, 10000).ToString();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (!_bool)
            {
                foreach (Thread t in _thread)
                {
                    if (t.ThreadState == ThreadState.Unstarted)
                    {
                        t.Start();
                    }
                    else if (t.ThreadState == ThreadState.Suspended || t.ThreadState == ThreadState.SuspendRequested || t.ThreadState == ThreadState.WaitSleepJoin || Convert.ToInt32(t.ThreadState) == 96)
                    {
                        //继续已经挂起的线程
                        t.Resume();
                        
                    }
                }
                button1.Text = "停止";
            }
            else
            {

                foreach (Thread t in _thread)
                {
                    t.Suspend();//挂起线程
                }           
                button1.Text = "开始";
            }

            _bool = !_bool;
        }
    }
}



猜你喜欢

转载自blog.csdn.net/m0_37137902/article/details/80680192
今日推荐