您的位置:首页 > 编程语言 > C#

C# 线程的暂停与恢复

2012-10-22 17:27 183 查看
这几天做一个小程序需要用到线程的暂停与恢复 ,搞来搞去用Thread.Suspend和Thread.Resume总达不到想要的结果。后来百度一下 总结写了一个方法,共享一下 ~~~~~~~~~~
public partial class Form1 : Form
{
AutoResetEvent are = new AutoResetEvent(false);//设置自动重置事件默认值为非终止状态
public Form1()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;//关闭文本框的跨线程操作检查
}

private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(fun);
t.IsBackground = true;
t.Start();
}
//在线程中执行的方法
private void fun()
{
int i = 0;
while (i<9999)
{
i += 1;
textBox2.Text = i.ToString();
if (textBox1.Text =="false")
{
are.WaitOne();//阻塞当前线程
}
}
}

private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "false";
}

private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = "true";
are.Set();//释放所有被阻塞的线程
}
}
界面:两个文本框和两个按钮
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: