2011年1月13日 星期四

C# 執行緒寫法

using System.Threading;
namespace testThread
{
    public partial class Form1 : Form
    {
        private work w1;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            if (w1 == null)
                w1 = new work();       
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // 啟動
            if (!w1.State())
                w1.Start();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            // 停止
            w1.Stop();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            // 暫停
            w1.Pause();
        }
        private void button4_Click(object sender, EventArgs e)
        {
            // 繼續
            w1.Resume();
        }
     }
    // 執行緒處理
    internal class work
    {     
        private ManualResetEvent ThreadControl = new ManualResetEvent(true);
        private Thread prog;
        public void Pause()
        {
            // 執行緒暫停
            ThreadControl.Reset();
        }
        public void Stop()
        {   
            // 執行緒停止
            ThreadControl.Set();
            prog.Abort();
        }
        public void Resume()
        {
            // 執行緒繼續
            ThreadControl.Set();
        }
        public void Start()
        {
            // 執行緒啟動
            if (prog == null || !prog.IsAlive)
            {              
                prog = new Thread(run);
                prog.Start();
            }
        }
        public bool State()
        {          
            // 執行緒狀態取得
            if (prog == null)
                return false;
            return prog.IsAlive;
        }
        public void run()
        {
            // 執行緒工作執行進入點
            while (true)
            {
                Thread.Sleep(1000); // 閒置時間
                // 當 ThreadControl 事件被設為 set 時,讓執行緒進入等待
                ThreadControl.WaitOne(-1);          
            }
        }
    }
}
// 參考 MSDN
// http://msdn.microsoft.com/zh-tw/library/system.threading.manualresetevent(VS.80).aspx