c# 多线程

admin 2021-05-17 19:59:51 466浏览 0评论
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.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Thread th;
        private void button1_Click(object sender, EventArgs e)
        {
            //创建一个线程
            th = new Thread(test);
            //将线程设置为后台线程
            th.IsBackground = true;
            //标记这个线程准备就绪,可以随时执行,具体什么时候执行这个线程由CPU决定
            th.Start();

        }

        private void test()
        {

            for (int i = 0; i < 10000; i++)
            {

                //Console.WriteLine(i);

                textBox1.Text = i.ToString();

                Thread.Sleep(3000);//停止3秒执行
            }

        }

        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();
            }
        }
    }
}


0条评论