C# thread02
C# thread02
功能:
01.主要實作如何利用類別(ThreadWithState)方式傳遞參數給執行緒
Code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading;//step 01 namespace CS_thread { public class ThreadWithState { private double value; public ThreadWithState(double number) { value = number; } public void ThreadProc() { while (true) { Form1.m_dblcount += this.value; Thread.Sleep(3000); } } } public partial class Form1 : Form { public static double m_dblcount; private Thread m_Thread = null; private Thread m_ClassThread = null; private 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_Thread = new Thread(new ThreadStart(threadFun)); m_Thread.Start(); tws = new ThreadWithState(20.0); m_ClassThread= new Thread(new ThreadStart(tws.ThreadProc)); 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(); } } } }