ASP.NET多线程范例1

 线程池的使用
using System;
using System.Threading;
using System.Collections;
namespace ASPNETThread
{
 //定义了一个结构
 public struct User
 {
  public string name;
  public DateTime lasttime; 
  public DateTime curtime;
  public string sessionid;
  public string iswhere;
 }    
 //定义在线用户类
 public class OnLineUser
 {
  private static ArrayList _alluser ;        //定义用户        
  public ArrayList alluser
  {
   get{return _alluser;}
   set{_alluser=value;}
  }        
  public OnLineUser()        //构造函数
  {
   if(_alluser==null)
   {
    _alluser=new ArrayList();   
   }
  }
  //功能说明:将当前用户加入在线列表
  //如果该用户的数据当前仍然在在线列表中,则暂时先不让该用户登陆,提示用户存在

  public bool  AddUserToOnLine(User user)
  {
   //需要先判断用户是否已经在用户列表中了
   if(_alluser==null)
   {
    _alluser.Add(user);
    return (true);
   }
   else
   {
    for ( int i = 0 ; i < _alluser.Count ; i ++)
    {
     //循环判断用户是否已经存在
     User tempuser = (User)_alluser[i] ;
     if(tempuser.sessionid.Equals(user.sessionid) && tempuser.name.Equals(user.name))
     {
      return(false);    //用户已经存在,则直接退出
     }
    }
    _alluser.Add(user);
    return (true);
   }
  }          
  //功能说明:判断某用户是否在线
  //返回值:TRUE代表在线,FALSE不在

  public  Boolean IsUserOnLine(string name)
  {
   //需要先判断用户是否已经在用户列表中了
   if(_alluser==null)
   {
    return (false);
   }
   else
   {
    for ( int i = 0 ; i < _alluser.Count ; i ++)
    {
     //循环判断用户是否已经存在
     User tempuser = (User)_alluser[i] ;
     if(tempuser.name.Equals(name))
     {
      return(true);
     }
    }
    return (false);
   }
  }        
  //功能说明:更新用户在线时间
  //返回值:最新的在线用户列表
  public Boolean CheckUserOnLine(string name)
  {
   //需要先判断用户是否已经在用户列表中了
   if(_alluser!=null)
   {
    for ( int i = 0 ; i < _alluser.Count ; i ++)
    {
     User  tempuser = (User)_alluser[i] ;
     //先判断当前用户是否是自己
     if(tempuser.name.Equals(name))
     {
      //更新用户在线时间
      tempuser.curtime=DateTime.Now;
      alluser[i]=tempuser;
      return(true);
     }
    }
   }
   return(false);
  }
 }
 public class CheckOnline
 {
  const int DELAY_TIMES = 5000 ;                //定义执行的时间间隔为5秒
  const int DELAY_SECONDS=30;                    //将用户掉线时间设置为30秒        
  private Thread thread ;                        //定义内部线程
  private static bool _flag=false;                    //定义唯一标志        
  public CheckOnline()
  {
   if (!_flag)
   {
    _flag= true;
    this.thread = new Thread(new ThreadStart(ThreadProc)) ;
    thread.Name = "online user" ;
    thread.Start() ;
   }
  }        
  internal void ThreadProc()
  {
   while(true)       
   {
    OnLineUser temp=new OnLineUser();        //定义一个用户对象
    for (int i=0 ;i< temp.alluser.Count;i++)
    {
     User tmpuser=(User)temp.alluser[i];
     if(tmpuser.curtime.AddSeconds(DELAY_SECONDS).CompareTo(DateTime.Now)<0)   
     {
      temp.alluser.RemoveAt(i);
     }
    }
    Thread.Sleep(DELAY_TIMES) ;                
   }
  }
 }
}


利用多线程
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Threading;
  private int[] valueArray;
  private Random randomNumber = new Random();
  private static volatile bool swaped = true;
  private DateTime startTime;
  private DateTime endTime;
  private static volatile string strng = "";
  private Hashtable threadHolder = new Hashtable();
  private static long threadCounter = 0;
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(Application["ThreadAndTime"]!=null)
   {
    tbResult.Text = Application["ThreadAndTime"].ToString();
    tbOut.Text = Application["OutTxt"].ToString();
   }
  }
  private void btnClearOut_Click(object sender, System.EventArgs e)
  {
   Application["OutTxt"] = "";
   tbOut.Text = "";
  }
  private void btnClearTime_Click(object sender, System.EventArgs e)
  {
   Application["ThreadAndTime"] = "";
   tbResult.Text = "";
  }
  private void btnSort_Click(object sender, System.EventArgs e)
  {
   btnSort.Enabled = false;
   valueArray = new int[Convert.ToInt32(ddlNum.SelectedItem.Text.Trim())];
   threadHolder.Clear();
   valueArray.Initialize();
   threadCounter = 0;
   lbMsg.Text = "排序进行中...";
   /* Insert value in to the valueArray */
   for(int i=0; i<valueArray.Length;i++)
   { 
    valueArray[i] = valueArray.Length-i; 
    //valueArray[i] = Convert.ToInt32(randomNumber.Next(1000));
   }
   /* Start a timer to check the time to sort the array */
   startTime = DateTime.Now;
   /* Start threads to sort the values in the arry */
   for(int t=0; t< Convert.ToInt32(ddlThreadNum.SelectedItem.Text.Trim());t++)
   {
    Thread thread = new Thread(new ThreadStart(Sort));
    thread.Name = Convert.ToString(t);
    thread.Start();
   }
   Page.RegisterStartupScript("","<script>window.setTimeout('location.href=location.href',5000);</script>");
  }
  public void Sort()
  { 
   try
   { 
    while(true)
    {
     swaped = false;
     for (int j = 0; j<valueArray.Length-1; j++)
     {     
      lock(typeof(Thread))
      { /* If the left-hand side value is greater swap values*/
       if(valueArray[j] > valueArray[j+1])
       {
        int T = valueArray[j];
        valueArray[j] = valueArray[j+1];
        valueArray[j+1] = T;
        swaped = true;
       }
      }
     }
     Thread.Sleep(1);
     if(!swaped) { break; }
    }
    Thread.CurrentThread.Abort();
   }  
   catch(Exception ex)
   {
     if( Interlocked.Increment(ref threadCounter) == Convert.ToInt64(ddlThreadNum.SelectedItem.Text.ToString().Trim()))
     Display();
   }
  }
  public void Display()
  {
   lbMsg.Text = "排序结束..";
   strng = "";
   endTime = DateTime.Now;
   for(int i=0; i< valueArray.Length; i++)
   { strng += valueArray[i].ToString()+" "; }
   btnSort.Enabled = true;
   TimeSpan ts = endTime-startTime;
   Application["ThreadAndTime"]+="Threads: "+ddlThreadNum.SelectedItem.Text.ToString().Trim()+" 所用毫秒数:"+Convert.ToString(ts.TotalMilliseconds)+"/r/n";
   Application["OutTxt"] = strng+"/r/n";
//   tbResult.Text +="Threads: "+ddlThreadNum.SelectedItem.Text.ToString().Trim()+" 所用毫秒数:"+Convert.ToString(ts.TotalMilliseconds)+"/r/n";
//   tbOut.Text = strng+"/r/n";
  }



using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Threading;
using System.IO;
  private ArrayList _pages;
  protected System.Web.UI.WebControls.Button btnNothread;
  private TimeSpan _timeSpent;
  public ArrayList SearchResults
  {
   get { return _pages; }
  }
  public TimeSpan timeSpent
  {
   get { return _timeSpent; }
  }
  public bool SearchWebSites(string keyword, string pURLs)
  {
   // start the timer
   DateTime lStarted = DateTime.Now;
   _pages = new ArrayList();   
   // split the urls string to an array
   string[] lURLs = pURLs.Split('/n');
   int lIdx;
   WebPage wp;
   // create the Thread array
   Thread[] t = new Thread[ lURLs.Length ];
   for ( lIdx = 0; lIdx < lURLs.Length; lIdx ++ )
   {
    // create a WebPage object for each url
    wp = new WebPage(keyword, lURLs[lIdx]);
    // add it to the _pages ArrayList
    _pages.Add( wp );
    // pass the search() method of the new WebPage object
    //  to the ThreadStart object. Then pass the ThreadStart
    //  object to the Thread object.

    t[lIdx] = new Thread( new ThreadStart( wp.search ) );
    // start the Thread object, which executes the search().
    t[lIdx].Start();
   }
   for ( lIdx = 0; lIdx < _pages.Count; lIdx ++ )
   {
    // waiting for all the Threads to finish.
    t[lIdx].Join();
   }
   // stop the timer.
   _timeSpent = DateTime.Now.Subtract( lStarted );
   return true;
  }
  public bool SingleThreadSearchWebSites(string keyword, string pURLs)
  {
   // start the timer
   DateTime lStarted = DateTime.Now;
   _pages = new ArrayList();   
   // split the urls string to an array
   string[] lURLs = pURLs.Split('/n');
   int lIdx;
   WebPage wp;
   for ( lIdx = 0; lIdx < lURLs.Length; lIdx ++ )
   {
    // create a WebPage object for each url
    wp = new WebPage(keyword, lURLs[lIdx]);
    _pages.Add( wp );
    wp.search();
   }
   // stop the timer.
   _timeSpent = DateTime.Now.Subtract( lStarted );
   return true;
  }
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }
  private void btnSearch_Click(object sender, System.EventArgs e)
  {
   if ( SearchWebSites( keyword.Text, urls.Text ) )
   {   
    info.Text = "找到 <font color=/"red/">" + SearchResults.Count + "</font> 个网页 ";
    info.Text += "包含上述关键字<font color=/"red/">/"" + keyword.Text + "</font>/". ";
    info.Text += "共花费时间: <font color=/"red/">" + timeSpent + "</font>";
    SearchForm.Visible = false;
    ResultList.DataSource = SearchResults;
    ResultList.DataBind();
   }
  }
  private void btnNothread_Click(object sender, System.EventArgs e)
  {
   if ( SingleThreadSearchWebSites( keyword.Text, urls.Text ) )
   {   
    info.Text = "找到 <font color=/"red/">" + SearchResults.Count + "</font> 个网页 ";
    info.Text += "包含上述关键字<font color=/"red/">/"" + keyword.Text + "</font>/". ";
    info.Text += "共花费时间: <font color=/"red/">" + timeSpent + "</font>";
    SearchForm.Visible = false;
    ResultList.DataSource = SearchResults;
    ResultList.DataBind();
   }
  }
 public class WebPage
 {  // private member fields.
  private int _instanceCount;
  private string _pageURL;
  private string _pageTitle;
  private string _keyword;
  private TimeSpan _timeSpent;
  public TimeSpan timeSpent
  {
   get { return _timeSpent; }
  }
  public int instanceCount
  {
   get { return _instanceCount; }
  }
  public string pageURL
  {
   get { return _pageURL; }
  }
  public string pageTitle
  {
   get { return _pageTitle; }
  }
  public WebPage() {}
  public WebPage(string keyword, string pageURL)
  {
   _keyword = keyword;
   _pageURL = pageURL;
  }
  public void search()
  {
   try
   {
    // start timing it
    DateTime lStarted = DateTime.Now;
    // create the WebRequest
    WebRequest webreq = WebRequest.Create( _pageURL );
    // connect to the page, and get its response
    WebResponse webresp = webreq.GetResponse();
    // wrap the response stream to a stream reader
    StreamReader sr = new StreamReader( webresp.GetResponseStream(), Encoding.ASCII );
    StringBuilder sb = new StringBuilder();
    string line;
    while ( ( line = sr.ReadLine()) != null )
    {
     // append each line the server sends, to the string builder
     sb.Append(line);
    }
    sr.Close();
    string pageCode = sb.ToString();
    // get the page title
    _pageTitle = getPageTitle( pageCode );
    // get the amount of time the keyword appeared on the page
    _instanceCount = countInstance( getPureContent( pageCode ) );
    // stop the timer
    _timeSpent = DateTime.Now.Subtract( lStarted );
   }
   catch(Exception ex)
   {
    string strM = ex.Message;
   }
  }
  // this method uses the regular expression to match the keyword.
  // it then count the matches to find out how many times the keyword appeared on the page.
  private int countInstance(string str)
  {
   string lPattern = "(" + _keyword + ")";
   int count = 0;
   try
   {
    Regex rx = new Regex(lPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled );
    StringBuilder sb = new StringBuilder();
    Match mt;
    for ( mt = rx.Match(str); mt.Success; mt = mt.NextMatch() )
     count ++ ;
   }
   catch(Exception ex)
   {
     string strM = ex.Message;
   }
   return count;
  }
  // this method uses the regular expression to match the pattern that represent all
  //  string enclosed between ">" and "<". It removes all the HTML tags,
  //  and only returns the HTML decoded content string.

  private string getPureContent(string str)
  {
   string lPattern = ">(?:(?<c>[^<]+))";
   StringBuilder sb = new StringBuilder();
   try
   {
    Regex rx = new Regex(lPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled );   
    Match mt;
    for ( mt = rx.Match(str); mt.Success; mt = mt.NextMatch() )
    {
     sb.Append( HttpUtility.HtmlDecode( mt.Groups["c"].ToString() ) );
     sb.Append( " " );
    }
   }
   catch(Exception ex)
   {
    string strM = ex.Message;
   }
   return sb.ToString();
  }
  // this method uses the regular expression to match the pattern that represent the
  //  HTML Title tag of the page. It only returns the first match, and ignores the rest.
  private string getPageTitle(string str)
  {
   string lTitle = "";
   string lPattern = "(?:<//s*title//s*>(?<t>[^<]+))";
   try
   {
    Regex rx = new Regex(lPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled );
    Match mt = rx.Match(str);
    if ( mt.Success )
     try
     {
      lTitle = mt.Groups["t"].Value.ToString();
     }
     catch
     {
      lTitle = "";
     }
    else
     lTitle = "";    
   }
   catch(Exception ex)
   {
     string strM = ex.Message;
   }
   return lTitle;
  }
 }
}

 

  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值