C#线程暂停与继续解决方案
昨天, 老师要我们每个人交一个关于黑客方面的程序,想了半天发现端口扫描工具好像好写点,从昨天写到今天基本快完成了,给大家看下效果,不要笑话我哦哦(~~)
图1 端口扫描器
这个程序里面有一些地方不太满意,就是扫描的暂停与继续实现时,使用的是Thread.Suspend和Thread.Resume而这两个方法,在VS2010里提示已经过时,不建议使用,在网上查阅了一些资料,发现有个事件通知的方法很好,事件通知的大致原理是,线程在执行过程中暂停,等到其他线程通知时才继续执行下去,这样的确是可以起到暂停与继续的效果。但是,这种暂停是被动的,我需要的是主动暂停,即点下按钮,线程暂停,再点下按钮,线程继续执行。
最终,我想了一种比较另类的方法,大致思路如下:还是采用事件通知的方式,在线程中等待通知,直到来通知了才继续执行,而主线程(窗体线程)中使用一个计时器System.Windows.Forms.Timer 来不停的通知线程,如果计时器间隔时间设置的足够小,基本上看不出停顿。此时,程序的暂停与继续实现就很简单了,相信大家已经想到了,只要在通过控制计时器的Stop()和Start()就可控制线程的暂停与继续了。
下面是一个下的demo:
运行截图:
图2 demo运行效果
C#源代码:
using System;
using System.Windows.Forms;
using System.Threading;
namespace 线程暂停与继续实现
{
public partial class Form1 : Form
{
//计时器
private System.Windows.Forms.Timer tm = new System.Windows.Forms.Timer();
//自动重置事件类
//主要用到其两个方法 WaitOne() 和 Set() , 前者阻塞当前线程,后者通知阻塞线程继续往下执行
AutoResetEvent autoEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
ProgressBar.CheckForIllegalCrossThreadCalls = false;
tm.Interval = 1;
tm.Tick += new EventHandler(tm_Tick);
}
//计时器 事件
void tm_Tick(object sender, EventArgs e)
{
autoEvent.Set(); //通知阻塞的线程继续执行
}
//启动
private void btnStart_Click(object sender, EventArgs e)
{
tm.Start();
Thread t = new Thread(DoWork);
t.Start();
}
//在线程中执行的方法
private void DoWork()
{
while (progressBar1.Value < progressBar1.Maximum)
{
progressBar1.PerformStep();
autoEvent.WaitOne(); //阻塞当前线程,等待通知以继续执行
}
}
//暂停
private void btnSuspend_Click(object sender, EventArgs e)
{
tm.Stop();
}
//继续
private void btnResume_Click(object sender, EventArgs e)
{
tm.Start();
}
}
}