知识要点:全局应用类,进程,线程
ASP.NET(十一)
知识要点:全局应用类,进程,线程
###全局应用程序类
Global.asax 文件,有时候叫做 ASP.NET 应用程序文件,提供了一种在一个中心位置响应应用程序级或模块级事件的方法。你可以使用这个文件实现应用程序安全性以及其它一些任务。注意**这个文件名一定不能改!!!**,新建后生成的方法如图(注意注释):
这里的全局异常处理方法通常是做日志处理,即捕捉到错误就写入日志,但是用户量大的情况下这会带来一个对文件操作的问题。。简单的高并发解决方案(队列):如果多个需要对一个文件进行操作,最好的做法是给这个文件上锁,但是如果用户量特写大把数据放在队列里,这样一来不会造成卡死,因为队列是对内存的操作,速度快,之后再找一个人把队列的数据再写入文件中。这个以后会详细来说。
线程 线程,可以简单理解为代码流 ,是windows任务调度的最小单位,是程序中的一个执行流。在理解线程之前,简单理解下进程。打开任务管理器你能看到各式各样的进程,进程包含运行一个程序所需要的资源,可用Process类进行操作 ,为解决在进程的创建,撤销切换等过程中系统为之付出的较大开销,可以就只切换进程里面的线程,当然线程是有优先级的。
线程的创建以及属性如下(以winform窗体为例):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public partial class Form1 : Form { public Form1 ( ) { InitializeComponent(); } private void button1_Click (object sender, EventArgs e ) { Thread thread = new Thread(StartJiSuan); thread.Priority = ThreadPriority.Normal; thread.Name = "hehehe" ; thread.IsBackground = true ; thread.Start(); thread.Join(1000 ); thread.Abort(); } private void StartJiSuan ( ) { int a = 0 ; for (int i = 0 ; i < 66666666 ; i++) { a = i; } MessageBox.Show(a.ToString()); } }
Thread类的参数都是委托 ,上面的代码是不带参,线程带参数写法如下
1 2 3 4 5 6 7 8 9 10 11 private void button2_Click (object sender, EventArgs e ) { int i = 10 ; Thread thread = new Thread(StartJiSuan2); thread.IsBackground = true ; thread.Start(i); } private void StartJiSuan2 (object i ) { i = (int )i; }
跨线程访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 private void button2_Click (object sender, EventArgs e ) { Thread thread = new Thread(ShowTextBoxResoult); thread.IsBackground = true ; thread.Start(10 ); } private void ShowTextBoxResoult (object o ) { int i = Convert.ToInt32(o); if (this .textBox1.InvokeRequired) { textBox1.Invoke(new Action<string , TextBox>(TextBoxVal), i.ToString(), textBox1); } } private void TextBoxVal (string arg1, TextBox arg2 ) { textBox1.Text = arg1; }
线程池的运用,线程的创建是非常消耗资源的,所以我们必须尽量使用线程池来创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Program { static void Main (string [] args ) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0 ; i < 1000 ; i++) { new Thread(() => { int sum = 1 + 1 ; }).Start(); } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); sw.Reset(); sw.Restart(); for (int i = 0 ; i < 1000 ; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback((state => { int j = 1 + 1 ; }))); } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); Console.ReadKey(); } }
可以看出执行的时间,上面没使用线程池的效率和下面是用线程池效率的对比,如果你想自己手动来销毁或者设置优先级那就只能自行去new了
线程的运用场景