Chapter 9. 线程

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 多线程
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Thread th;

        private void button1_Click(object sender, EventArgs e)
        {
            //创建一个线程去执行Test方法
            th = new Thread(Test);

            //将线程设置为后台线程
            th.IsBackground = true;

            //标记这个线程准备就绪,可以随时被执行,
            //但具体什么时候执行,由cpu决定
            //括号里为Test方法的参数
            th.Start(10000);

            //线程休眠3秒后执行
            Thread.Sleep(3000);
        }

        /// <summary>
        /// 显示n以内的数
        /// </summary>
        /// <param name="n"></param>
        private void Test(object n)
        {
            int count = Convert.ToInt32(n);
            for (int i = 0; i <= count; i++)
            {
                textBox1.Text = i.ToString();

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取消跨线程的访问
            Control.CheckForIllegalCrossThreadCalls = false;

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //当点击关闭窗体的时候,判断新线程是否为null
            if (th != null)
            {
                //结束这个线程
                th.Abort();
            }
        }
    }
}

原文地址:https://www.cnblogs.com/xiao55/p/5651574.html