如何在asp.net中,把一个线程,在服务器上创建
在网页上要作个检测用户在线的系统,方法写好了,但是这个线程怎么让它在服务器上创建,而不是客户端上创建 --------------------编程问答-------------------- 线程肯定在服务器上创建你如果能做到在客户端创建,那么你的做法很“流氓”了 --------------------编程问答-------------------- Global.asax中
void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
}
void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
} --------------------编程问答-------------------- asp.net的hosting是w3wp, 它启动的线程都是在服务器端的,关于线程的相关操作,查看System.Threading命名空间。
--------------------编程问答-------------------- Global.asax
using System;
using System.Threading;
// Simple threading scenario: Start a static method running
// on a second thread.
public class ThreadExample {
// The ThreadProc method is called when the thread starts.
// It loops ten times, writing to the console and yielding
// the rest of its time slice each time, and then ends.
public static void ThreadProc() {
for (int i = 0; i < 10; i++) {
Console.WriteLine("ThreadProc: {0}", i);
// Yield the rest of the time slice.
Thread.Sleep(0);
}
}
public static void Main() {
Console.WriteLine("Main thread: Start a second thread.");
// The constructor for the Thread class requires a ThreadStart
// delegate that represents the method to be executed on the
// thread. C# simplifies the creation of this delegate.
Thread t = new Thread(new ThreadStart(ThreadProc));
// Start ThreadProc. Note that on a uniprocessor, the new
// thread does not get any processor time until the main thread
// is preempted or yields. Uncomment the Thread.Sleep that
// follows t.Start() to see the difference.
t.Start();
//Thread.Sleep(0);
for (int i = 0; i < 4; i++) {
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(0);
}
Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
t.Join();
Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program.");
Console.ReadLine();
}
}
--------------------编程问答-------------------- asp.net中服务器端使用线程有这个必要吗?网页上要作个检测用户在线,一定要使用线程的话 可以
bool mailThreadStarted = false;
protected virtual void Application_Start(object sender, EventArgs e)
{
Application.Lock();
if(!mailThreadStarted)
{
Thread th = new Thread(CheckUserOnline);
th.IsBackground = true;
th.Start();
mailThreadStarted = true;
}
Application.UnLock();
}
private void CheckUserOnline()
{
while(true)
{
//CheckUserOnline code
Thread.Sleep(...);
}
}
考虑客户端插件,比如ACTIVEX --------------------编程问答-------------------- 如果服务器不是多CPU的话,线程是减少效率的。需要CPU资源的任务首先可以考虑经常闲置的客户端。
补充:.NET技术 , ASP.NET