背景:
阅读新闻

多线程例子

  作者: 今日评论: [字体: ]

source from:http://www.codeproject.com/KB/cs/workerthread.aspx

后台处理类

    public class BackWorker
    {
        public delegate void DelegateAddString(String s);
        public delegate void DelegateThreadFinished();

        public DelegateAddString m_DelegateAddString;
        public DelegateThreadFinished m_DelegateThreadFinished;

        // Main thread sets this event to stop worker thread:
        public ManualResetEvent m_EventStopThread;

        // Worker thread sets this event when it is stopped:
        public ManualResetEvent m_EventThreadStopped;


        public BackWorker()
        {
            // initialize events
            m_EventStopThread = new ManualResetEvent(false);
            m_EventThreadStopped = new ManualResetEvent(false);
        }

        public void Start()
        {
            int i;
            String s;

            for (i = 1; i <= 101; i++)
            {
                // make step
                s = "Step number " + i.ToString() + " executed";

                Thread.Sleep(1000);

                // Make synchronous call to main form.
                // MainForm.AddString function runs in main thread.
                // To make asynchronous call use BeginInvoke
                //m_form.Invoke(m_form.m_DelegateAddString, new Object[] { s });
                this.m_DelegateAddString(s);

                // check if thread is cancelled
                if (m_EventStopThread.WaitOne(0, true))
                {
                    // clean-up operations may be placed here
                    // ...

                    // inform main thread that this thread stopped
                    m_EventThreadStopped.Set();

                    return;
                }
            }

            // Make asynchronous call to main form
            // to inform it that thread finished
            this.m_DelegateThreadFinished();
        }
    }

前台Form

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        // worker thread
        Thread m_WorkerThread;
        BackWorker bw = null;
        private void btnStartThread_Click(object sender, EventArgs e)
        {
            this.richTextBox1.Clear();
            this.btnStartThread.Enabled = false;
            this.btnStopThread.Enabled = true;

            this.bw = new BackWorker();

            // initialize delegates
            bw.m_DelegateAddString += new WindowsFormsApplication1.BackWorker.DelegateAddString(this.AddString);
            bw.m_DelegateThreadFinished += new WindowsFormsApplication1.BackWorker.DelegateThreadFinished(this.ThreadFinished);

            m_WorkerThread = new Thread(new ThreadStart(bw.Start));
            m_WorkerThread.Name = "Worker Thread Sample"; // looks nice in Output window
            m_WorkerThread.Start();
        }
        private void AddString(String s)
        {
            if (this.InvokeRequired)
            {
                //this.Invoke(AddString, new Object[] { s });
                //this.Invoke(this.AddString, new String[] { s });
                this.Invoke(new BackWorker.DelegateAddString(this.AddString), new Object[] { s });
            }
            else
            {
                this.richTextBox1.AppendText("\r\n" + s);
            }
        }

        private void ThreadFinished()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new BackWorker.DelegateThreadFinished(this.ThreadFinished), null);
            }
            else
            {
                this.btnStartThread.Enabled = true;
                this.btnStopThread.Enabled = false;
            }
        }

        // Stop worker thread if it is running.
        // Called when user presses Stop button of form is closed.
        private void StopThread()
        {
            if (m_WorkerThread != null && m_WorkerThread.IsAlive)  // thread is active
            {
                // set event "Stop"
                this.bw.m_EventStopThread.Set();
                // this.bw.Stop();

                // wait when thread  will stop or finish
                while (m_WorkerThread.IsAlive)
                {
                    // We cannot use here infinite wait because our thread
                    // makes syncronous calls to main form, this will cause deadlock.
                    // Instead of this we wait for event some appropriate time
                    // (and by the way give time to worker thread) and
                    // process events. These events may contain Invoke calls.
                    if (WaitHandle.WaitAll((new ManualResetEvent[] { this.bw.m_EventThreadStopped }), 100, true))
                    {
                        break;
                    }
                    Application.DoEvents();
                }
            }
            ThreadFinished();// set initial state of buttons
        }


        // Stop Thread button is pressed
        private void btnStopThread_Click(object sender, System.EventArgs e)
        {
            StopThread();
        }
        // Exit button is pressed.
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }
        // Form is closed.
        // Stop thread if it is active.
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            StopThread();
        }
    }

 

来源:
录入日期:[2012-1-17 15:42:00]
收藏 推荐 打印 | 录入:mikebai | 阅读:
文章评论      
正在加载评论列表...
评论表单加载中...