您的位置:首页 > 其它

线程暂停与继续

2013-10-11 16:08 260 查看
这篇文章主要是答复百度网友的问题的,代码做了注释,就不解释了。线程的暂停,我使用了WaitOne方法,线程的继续,则使用了set方法,其实,这两种方法都存在于AutoResetEvent类中,这个类主要是通过设置信号量来实现线程的暂停与继续的。

代码如下:

usingSystem;

[code]usingSystem.Windows.Forms;
usingSystem.Threading;


namespaceThreadInUI

{

publicpartialclassForm1:Form

{

publicForm1()

{

InitializeComponent();

for(inti=0;i<11;i++)

{

a[i]=newAutoResetEvent(false);//初始化

b[i]=newAutoResetEvent(false);

}

}


string[]threadID=newstring[11];

AutoResetEvent[]a=newAutoResetEvent[11];

AutoResetEvent[]b=newAutoResetEvent[11];

privatevoidbtnStart_Click(objectsender,EventArgse)

{

lblLog.Invoke((Action)(()=>{lblLog.Text+="\r\n当前主线程ID为:"+Thread.CurrentThread.ManagedThreadId.ToString();}));

for(inti=0;i<10;i++)

{

intj=i;//这个用于避免闭包

Threadt=newThread(newThreadStart(()=>

{

a[j].WaitOne();//这个用于获取子线程的ID

lblLog.Invoke((Action)(()=>{lblLog.Text+="\r\n线程"+threadID[j]+"睡眠3s";}));

Thread.Sleep(3000);

lblLog.Invoke((Action)(()=>{lblLog.Text+="\r\n线程"+threadID[j]+"暂停";}));

b[j].WaitOne();//这个用于暂停所有子线程的运作

lblLog.Invoke((Action)(()=>{lblLog.Text+="\r\n===线程"+threadID[j]+"恢复===";}));

}));

threadID[i]=t.ManagedThreadId.ToString();

a[j].Set();//当子线程的ID生成后,这里放行,目的是避免取不到Thread的ID

t.Start();

}

}


privatevoidbtnGoOn_Click(objectsender,EventArgse)

{

for(inti=0;i<10;i++)

{

b[i].Set();//放行所有的子线程

}

}

}

}

[/code]

实现的效果如下:

当点击“打开10个线程并阻塞”按钮的时候:





当点击“继续运行10个线程”按钮的时候:





代码很简单,源码我就不加上了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: