啟動一個新線程。使用new Thread(),創(chuàng)建一個新的線程,并調(diào)用Start()方法。在阻塞狀態(tài)下調(diào)用Interrupt()會引發(fā)ThreadInterruptedException異常。通常用于中斷被阻塞的線程。阻塞調(diào)用線程,直到被調(diào)用的線程完成執(zhí)行。案例:啟動線程后文本框中數(shù)據(jù)每隔1s加1,并顯示在文本框中。namespace _015_Thread相關(guān)方法{ public partial class Thread相關(guān)方法 : Form { public Thread相關(guān)方法() { InitializeComponent(); }
private Thread thread=null; int num = 0;
private void btStart_Click(object sender, EventArgs e) { thread = new Thread(() => { while (true) { Thread.Sleep(1000); this.txtBox.Invoke(new Action(() => { this.txtBox.Text += num++ + "、".ToString(); })); } }); thread.Start(); } private void btSuspend_Click(object sender, EventArgs e) { if (thread.ThreadState==ThreadState.Running||thread.ThreadState==ThreadState.WaitSleepJoin) { thread.Suspend(); } } private void btResume_Click(object sender, EventArgs e) { if (thread.ThreadState == ThreadState.Suspended) { thread.Resume(); } } private void btInterrupt_Click(object sender, EventArgs e) { thread.Interrupt(); } private void btAbort_Click(object sender, EventArgs e) { thread.Abort(); } private void btJoin_Click(object sender, EventArgs e) { thread = new Thread(() => { Thread.Sleep(5000); MessageBox.Show("等待此線程執(zhí)行完后,再執(zhí)行等待線程"); });
thread.Start(); thread.Join(); MessageBox.Show("5s后彈出此窗口"); } }}
閱讀原文:原文鏈接
該文章在 2025/4/21 10:24:13 編輯過