指定时间终止线程?

public   class   WebForm1   :   System.Web.UI.Page  
  {  
  private   UdpClient   server;  
  private   IPEndPoint   receivePoint; //将网络端点表示为IP地址和端口号  
  private   IPEndPoint   sendPoint; //本地网络端点  
  private   int   port   =   1171; //本地的端口号  
  private   int   desPort   =   20048; //远端机顶盒的端口号  
  private   Thread   startServer;  
  private   Thread   setThreadFlag; //用于设置startServer线程的  
  private   bool   threadFlag;  
  private   StringBuilder   sb   =   new   StringBuilder();  
   
  protected   System.Web.UI.WebControls.Label   Label1;  
   
  private   void   Page_Load(object   sender,   System.EventArgs   e)  
  {  
  if   (!IsPostBack)  
  {  
  Run();  
  }  
  }  
   
  #region   Web   窗体设计器生成的代码  
  override   protected   void   OnInit(EventArgs   e)  
  {  
  //  
  //   CODEGEN:   该调用是   ASP.NET   Web   窗体设计器所必需的。  
  //  
  InitializeComponent();  
  base.OnInit(e);  
  }  
   
  ///   <summary>  
  ///   设计器支持所需的方法   -   不要使用代码编辑器修改  
  ///   此方法的内容。  
  ///   </summary>  
  private   void   InitializeComponent()  
  {          
  this.Load   +=   new   System.EventHandler(this.Page_Load);  
   
  }  
  #endregion  
   
  ///   <summary>  
  ///   开启一个线程执行UDP服务  
  ///   </summary>  
  private   void   Run()  
  {  
   
  server   =   new   UdpClient(port);  
   
  receivePoint   =   new   IPEndPoint(IPAddress.Broadcast,   port);  
  sendPoint   =   new   IPEndPoint(IPAddress.Broadcast,   desPort);  
   
  //开启一个线程  
  startServer   =   new   Thread(new   ThreadStart(StartServer));  
  setThreadFlag   =   new   Thread(new   ThreadStart(SetThreadFlag));  
  startServer.Start();  
  setThreadFlag.Start();  
   
  Label1.Text   =   sb.ToString();  
   
  startServer.Abort();  
  setThreadFlag.Abort();  
  }  
   
  ///   <summary>  
  ///   执行UDP服务  
  ///   </summary>  
  private   void   StartServer()  
  {  
  threadFlag   =   true;  
   
  byte[]   receiveData;  
  ASCIIEncoding   encode   =   new   ASCIIEncoding();  
   
  byte[]   sendData   =   encode.GetBytes("Query:FFFFFF");  
  server.Send(sendData,   sendData.Length,   sendPoint);  
   
  while(threadFlag)  
  {  
  //接收从远程主机发送到本地的数据  
  receiveData   =   server.Receive(ref   receivePoint);  
   
  string   receiveString   =   encode.GetString(receiveData);  
  sb.Append("Data:   "   +   receiveString);  
  sb.Append("<br>");  
  sb.Append("IP:   "   +   receivePoint.Address);  
  sb.Append("<br>");  
  sb.Append("Port:   "   +   receivePoint.Port);  
  sb.Append("<br>");  
  }  
  }  
   
  private   void   SetThreadFlag()  
  {  
  Thread.Sleep(1000);  
  threadFlag   =   false;  
  }  
  }   
 
posted on 2008-01-08 11:26  ringnet  阅读(475)  评论(0编辑  收藏  举报