C#Thread相关方法
|
admin
2025年4月19日 20:53
本文热度 1360
|
启动一个新线程。使用new Thread(),创建一个新的线程,并调用Start()方法。在阻塞状态下调用Interrupt()会引发ThreadInterruptedException异常。通常用于中断被阻塞的线程。案例:启动线程后文本框中数据每隔1s加1,并显示在文本框中。namespace _015_Thread相关方法{ public partial class Thread相关方法 : Form { public Thread相关方法() { 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("等待此线程执行完后,再执行等待线程"); });
thread.Start(); thread.Join(); MessageBox.Show("5s后弹出此窗口"); } }}
阅读原文:原文链接
该文章在 2025/4/21 10:24:13 编辑过