C# thread03

C# thread03

C# thread03

功能:
    01.主要實作執行緒開啟/中斷切換


Code:

using System.Threading;//step 01 
namespace CS_thread 
{ 
	public partial class Form1 : Form 
	{
		public static double m_dblcount;
		public static Thread m_Thread = null;
		public static Thread m_ClassThread = null;
		public static ThreadWithState tws;
		delegate void SetTextCallback(string text);
		public Form1()
		{
			InitializeComponent();
			m_dblcount = 0.0;
		} 
		public void threadFun()
		{ 
			while (true)
			{ 
				//Form1.m_dblcount += 1.0; 
				String StrBuf; 
				StrBuf=Convert.ToString(Form1.m_dblcount); 
				SetText(StrBuf); 
				Thread.Sleep(3000); 
			}
		} 
		
		public void SetText(string text) 
		{
			if (this.textBox1.InvokeRequired)
			{ 
				SetTextCallback d = new SetTextCallback(SetText);
				this.Invoke(d, new object[] { text });
			} 
			else
			{ 
				this.textBox1.Text = text; 
			}
		} 
		
		private void button1_Click(object sender, EventArgs e) 
		{
			m_dblcount = 0.0; 
			m_Thread = new Thread(new ThreadStart(threadFun)); 
			if (!m_Thread.IsAlive)
			{ 
				m_Thread.Start();
			}
			tws = new ThreadWithState(20.0);
			m_ClassThread= new Thread(new ThreadStart(tws.ThreadProc)); 
			
			if (!m_ClassThread.IsAlive) 
			{
				m_ClassThread.Start();
			} 
		} 
		
		private void Form1_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (m_Thread.IsAlive) 
			{ 
				m_Thread.Abort(); 
			} 
			
			if (m_ClassThread.IsAlive) 
			{ 
				m_ClassThread.Abort();
			} 
		} 
		
		private void button2_Click(object sender, EventArgs e) 
		{ 
			if (m_Thread.IsAlive)
			{
				m_Thread.Abort();
			} 
			if (m_ClassThread.IsAlive) 
			{
				m_ClassThread.Abort();
			}
		}
	}
} 


發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *