您的位置:首页 > 移动开发 > Objective-C

线程初识,为什么Abort()了不能再start

2011-03-22 17:38 337 查看
2011-03-22

今天第一天学习线程知识,顺便来做下笔记~~

以下是代码:

using System;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private Thread thread1 = new Thread(new ThreadStart(FormShow1));

 

        public Form1()
        {
            InitializeComponent();
        }

        private void Threa1Start_Click(object sender, EventArgs e)
        {
            thread1.Start();
            buttom();
            textBox1.Text += "thread1.IsAlive:" + thread1.IsAlive + "/r/n";
        }

        private void Threa1Stop_Click(object sender, EventArgs e)
        {
            thread1.Abort();
            thread1.Join();
            FormShowStop1();
            buttom();
            textBox1.Text += "thread1.IsAlive:" + thread1.IsAlive + "/r/n";
        }
     
        private static void FormShow1()
        {
            MessageBox.Show("线程1启动");
        }

        private void FormShowStop1()
        {
            MessageBox.Show("线程1停止");
        }
     
        private void buttom()
        {
            if (thread1.ThreadState == ThreadState.Running)
            {
                Threa1Stop.Enabled = true;
                Threa1Start.Enabled = false;
            }
            else
            {
                Threa1Stop.Enabled = false;
                Threa1Start.Enabled = true;
            }          
        }        
    }
}

以上代码初次运行没问题,但点击Threa1Stop停止后,再点击开始就没办了~~~问了一下google~

原来每次线程结束了,需要重新再new一次才可以正常进行~~~

于是改成:

 private Thread thread1 = null;

 

再把

private void Threa1Start_Click(object sender, EventArgs e)
        {
            this.thread1 =new Thread(new ThreadStart(FormShow1));
            thread1.Start();
            buttom();
            textBox1.Text += "thread1.IsAlive:" + thread1.IsAlive + "/r/n";
        }

再运行,OK~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息