C#线程实现暂停与继续

C#线程暂停与继续解决方案

原帖地址:http://blog.csdn.net/xiaohui_hubei/article/details/7494553

           昨天, 老师要我们每个人交一个关于黑客方面的程序,想了半天发现端口扫描工具好像好写点,从昨天写到今天基本快完成了,给大家看下效果,不要笑话我哦哦(~~)

端口扫描器

图1  端口扫描器

        这个程序里面有一些地方不太满意,就是扫描的暂停与继续实现时,使用的是Thread.Suspend和Thread.Resume而这两个方法,在 VS2010里提示已经过时,不建议使用,在网上查阅了一些资料,发现有个事件通知的方法很好,事件通知的大致原理是,线程在执行过程中暂停,等到其他线 程通知时才继续执行下去,这样的确是可以起到暂停与继续的效果。但是,这种暂停是被动的,我需要的是主动暂停,即点下按钮,线程暂停,再点下按钮,线程继 续执行。

         最终,我想了一种比较另类的方法,大致思路如下:还是采用事件通知的方式,在线程中等待通知,直到来通知了才继续执行,而主线程(窗体线程)中使用一个计 时器System.Windows.Forms.Timer 来不停的通知线程,如果计时器间隔时间设置的足够小,基本上看不出停顿。此时,程序的暂停与继续实现就很简单了,相信大家已经想到了,只要在通过控制计时 器的Stop()和Start()就可控制线程的暂停与继续了。

下面是一个下的demo:

运行截图:

图2  demo运行效果

C#源代码:

    1. using System;  
    2. using System.Windows.Forms;  
    3. using System.Threading;  
    4.   
    5. namespace 线程暂停与继续实现  
    6. {  
    7.     public partial class Form1 : Form  
    8.     {  
    9.         //计时器  
    10.         private System.Windows.Forms.Timer tm = new System.Windows.Forms.Timer();  
    11.         //自动重置事件类    
    12.         //主要用到其两个方法 WaitOne() 和 Set() , 前者阻塞当前线程,后者通知阻塞线程继续往下执行  
    13.         AutoResetEvent autoEvent = new AutoResetEvent(false);  
    14.   
    15.         public Form1()  
    16.         {  
    17.             InitializeComponent();  
    18.             ProgressBar.CheckForIllegalCrossThreadCalls = false;  
    19.             tm.Interval = 1;  
    20.             tm.Tick += new EventHandler(tm_Tick);  
    21.         }  
    22.   
    23.         //计时器 事件  
    24.         void tm_Tick(object sender, EventArgs e)  
    25.         {  
    26.             autoEvent.Set(); //通知阻塞的线程继续执行  
    27.         }  
    28.   
    29.         //启动  
    30.         private void btnStart_Click(object sender, EventArgs e)  
    31.         {  
    32.             tm.Start();  
    33.   
    34.             Thread t = new Thread(DoWork);  
    35.             t.Start();  
    36.         }  
    37.           
    38.         //在线程中执行的方法  
    39.         private void DoWork()  
    40.         {  
    41.             while (progressBar1.Value < progressBar1.Maximum)  
    42.             {  
    43.                 progressBar1.PerformStep();  
    44.                 autoEvent.WaitOne();  //阻塞当前线程,等待通知以继续执行  
    45.             }  
    46.         }  
    47.   
    48.         //暂停  
    49.         private void btnSuspend_Click(object sender, EventArgs e)  
    50.         {  
    51.             tm.Stop();  
    52.         }  
    53.   
    54.         //继续  
    55.         private void btnResume_Click(object sender, EventArgs e)  
    56.         {  
    57.             tm.Start();  
    58.         }  
    59.     }  

原文地址:https://www.cnblogs.com/xingvskong11/p/Thread.html