2007年8月9日 星期四

使用 thread

// Global.asax.cs



using System;

using System.Collections;

using System.ComponentModel;

using System.Web;

using System.Web.SessionState;

using System.Threading;



namespace test

{

/// <summary>

/// Summary description for Global.

/// </summary>

public class Global : System.Web.HttpApplication

{

/// <summary>

/// Required designer variable.

/// </summary>

private System.ComponentModel.IContainer components = null;





//記錄 thread 每次會去設定的變數

public static string strKeep;



//宣告我們所要產生的 thread

public static Thread checkThread;





//宣告讓 thread 等待的時間

static TimeSpan waitTime = new TimeSpan(0, 0, 10);//hh,mm,ss





public Global()

{

InitializeComponent();

}



protected void Application_Start(Object sender, EventArgs e)

{r>


//start a thread to do AddKeep( ) method



ThreadStart threadDelegate = new ThreadStart(AddKeep);

checkThread = new Thread(threadDelegate);

checkThread.IsBackground = true;

checkThread.Start();

}

 

protected void Session_Start(Object sender, EventArgs e)

{





if(!checkThread.IsAlive)

{

ThreadStart threadDelegate = new ThreadStart(AddKeep);

checkThread = new Thread(threadDelegate);

checkThread.IsBackground = true;

checkThread.Start();

}







}



protected void Application_BeginRequest(Object sender, EventArgs e)

{



}



protected void Application_EndRequest(Object sender, EventArgs e)

{



}



protected void Application_AuthenticateRequest(Object sender, EventArgs
e)

{



}



protected void Application_Error(Object sender, EventArgs e)

{



}



protected void Session_End(Object sender, EventArgs e)

{



}



protected void Application_End(Object sender, EventArgs e)

{r>


}



public static void AddKeep()

{

while(true)

{

try

{

strKeep=string.Format("{0}",int.Parse(strKeep)+1);

}

catch

{

strKeep="0";

}



Thread.Sleep( waitTime );

}



}



#region Web Form Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{   

this.components = new System.ComponentModel.Container();

}

#endregion

}br>
}

 

沒有留言:

張貼留言