中如何讓一個按鈕去啟動一個線程?
這個需要用到后臺線程執行,否則一運行主線程就卡住了:
public partial class Form1 : Form { // 打印放在后臺執行 BackgroundWorker m_Worker; // 用一個標記來看是否請求停止執行 bool m_NeedRun = false; public Form1() { InitializeComponent(); m_Worker = new BackgroundWorker(); m_Worker.DoWork += new DoWorkEventHandler(m_Worker_DoWork); } void m_Worker_DoWork(object sender, DoWorkEventArgs e) { while( m_NeedRun ) // 后臺可以循環打印,不影響主線程的運行 Console.Write( "xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyy" ); } private void button1_Click(object sender, EventArgs e) { m_NeedRun = true; m_Worker.RunWorkerAsync(); } private void button2_Click(object sender, EventArgs e) { m_NeedRun = false; } }