C# terminate thread with stop variable

来源:互联网 发布:淘宝头条问答 编辑:程序博客网 时间:2024/06/08 08:19

namespace FrameworkTest
{
    public partial class Form1 : Form
    {
        private bool stopThread = false;
        delegate void InsertListCallback(int index, object item);

        private void btnStart_Click(object sender, EventArgs e)
        {
            stopThread = false;

            Thread t = new Thread(ThreadProc);
            t.IsBackground = true;
            t.Start();
        }

        private void ThreadProc()
        {
            int i = 0;
            while (!stopThread)
            {
                this.Invoke(new InsertListCallback(
                    listBox1.Items.Insert),
                    new object[] { 0, i.ToString() });
                Thread.Sleep(20);
                i++;
            }

            if (stopThread)
                this.Invoke(new InsertListCallback(
                    listBox1.Items.Insert),
                    new object[] { 0, "thread was stoped" });
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            stopThread = true;
        }
    }
}
原创粉丝点击