.net使用线程与线程处理

1.线程的创建

   .net是通过Thread类来描述线程的,线程的创建即构造Thread类即可。

    Thread常用的构造函数有两个,分别是:

   Thread(ThreadStart)  与 Thread(ParameterizedThreadStart) 。

   其中:ThreadStart是一个委托,定义如下:public delegate void ThreadStart()

               ParameterizedThreadStart也是一个委托,定义如下:public delegate void ParameterizedThreadStart(Object obj)

    二者的区别是ParameterizedThreadStart是一个能够使用一个object对象作为参数的委托。其中参数通过 Thread.Start(Object para)

   方式进行参数的确定。

    1.1使用ThreadStart创建线程举例:

  1. using System;
  2. using System.Threading;
  3. class Test
  4. {
  5.     static void Main() 
  6.     {
  7.         Thread newThread = 
  8.             new Thread(new ThreadStart(Work.DoWork));
  9.         newThread.Start();
  10.     }
  11. }
  12. class Work 
  13. {
  14.     Work() {}
  15.     public static void DoWork() {}
  16. }

当然在使用委托时可以简化使用方式,如:

 Thread newThread=new Thread(Work.DoWork);

 

    1.2使用ParameterizedThreadStart创建线程举例:

  1. using System;
  2. using System.Threading;
  3. public class Work
  4. {
  5.     public static void Main()
  6.     {
  7.         // To start a thread using a shared thread procedure, use
  8.         // the class name and method name when you create the 
  9.         // ParameterizedThreadStart delegate. C# infers the 
  10.         // appropriate delegate creation syntax:
  11.         //    new ParameterizedThreadStart(Work.DoWork)
  12.         //
  13.         Thread newThread = new Thread(Work.DoWork);
  14.         // Use the overload of the Start method that has a
  15.         // parameter of type Object. You can create an object that
  16.         // contains several pieces of data, or you can pass any 
  17.         // reference type or value type. The following code passes
  18.         // the integer value 42.
  19.         //
  20.         newThread.Start(42);
  21.         // To start a thread using an instance method for the thread 
  22.         // procedure, use the instance variable and method name when 
  23.         // you create the ParameterizedThreadStart delegate. C# infers 
  24.         // the appropriate delegate creation syntax:
  25.         //    new ParameterizedThreadStart(w.DoMoreWork)
  26.         //
  27.         Work w = new Work();
  28.         newThread = new Thread(w.DoMoreWork);
  29.         // Pass an object containing data for the thread.
  30.         //
  31.         newThread.Start("The answer.");
  32.     }
  33.     public static void DoWork(object data)
  34.     {
  35.         Console.WriteLine("Static thread procedure. Data='{0}'",
  36.             data);
  37.     }
  38.     public void DoMoreWork(object data)
  39.     {
  40.         Console.WriteLine("Instance thread procedure. Data='{0}'",
  41.             data);
  42.     }
  43. }

1.2线程的终止

 

       可以调用Abort方法终止线程。线程是如何终止自己的呢?线程终止的过程是在线程外(比如主线程)调用该线程对象的Abort方法,该方法会使该线程在运行过程中出现一个异常 ThreadAbortException ,该异常可以在线程内被捕捉到。被终止的线程在被Abort以后,不再去执行正常的代码,而是捕获到异常转而执行 catch{}finally{}的代码。这说明,线程并不是立即退出的,而是继续执行一段善后的代码。所以在调用Abort时,最好继续调用Join()函数,让线程执行完善后代码再退出。

      如果被终止的线程正在运行中,调用Abort则会中止后续代码的运行;如果被终止的线程处于 WaitSleepJoin状态,那么该线程会被中断然后中止(即线程被唤醒然后中止)。

  1. using System;
  2. using System.Threading;
  3. class Test
  4. {
  5.     public static void Main()
  6.     {
  7.         Thread newThread  = new Thread(new ThreadStart(TestMethod));
  8.         newThread.Start();
  9.         Thread.Sleep(1000);
  10.         // Abort newThread.
  11.         Console.WriteLine("Main aborting new thread.");
  12.         try
  13.        {
  14.         newThread.Abort("Information from Main.");
  15.        }
  16.        catch(ThreadAbortException)
  17.        {
  18.               Console.WriteLine("main catch the ThreadAbortException");
  19.        }
  20.         // Wait for the thread to terminate.
  21.         newThread.Join();
  22.         Console.WriteLine("New thread terminated - Main exiting.");
  23.     }
  24.     static void TestMethod()
  25.     {
  26.         try
  27.         {
  28.             while(true)
  29.             {
  30.                 Console.WriteLine("New thread running.");
  31.                 Thread.Sleep(1000);
  32.             }
  33.         }
  34.         catch(ThreadAbortException abortException)
  35.         {
  36.             Console.WriteLine((string)abortException.ExceptionState);
  37.         }
  38.     }
  39. }
  40. 注:在上述代码中,main函数是无法捕获ThreadAbortException异常的。

1.3线程的阻塞

      引起线程阻塞的方法有静态方法Sleep(),因为是静态方法所以只能由线程自身完成阻塞过程,并且线程立即进入阻塞状态。是一种主动的阻塞。

      Join()则是阻塞调用线程而等待使工作线程运行完毕。

     注意:Thread.CurrentThread.Join()与Sleep()容易产生混淆,二者都是使当前线程阻塞。区别好像是在处理一些非托管的资源时使用 Thread.CurrentThread.Join()而不是Sleep(),MSDN如此解释:“在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程,直到某个线程终止为止。”

 

1.4线程的唤醒

     使用Abort以及Interrupt都能使处于WaitSleepJoin中的线程产生中断唤醒,区别在于Abort是使线程终止,而Interrupt是使中断一个线程仅仅释放它的当前的(或下一个)等待状态,它并不结束这个线程。

    ThreadInterruptedException 在中断的线程中引发,但要在该线程阻塞之后才引发。如果该线程一直未阻塞,则一直都不会引发该异常,因而该线程可能无需中断就能完成。下面的例子(稍不同于MSDN上写得),可以看出Interrupt的确没有终止线程。

 


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. namespace InterruptTest
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             StayAwake stayAwake = new StayAwake();
  13.             Thread newThread =
  14.                 new Thread(new ThreadStart(stayAwake.ThreadMethod));
  15.             newThread.IsBackground = true;
  16.             newThread.Start();
  17.             // The following line causes an exception to be thrown 
  18.             // in ThreadMethod if newThread is currently blocked
  19.             // or becomes blocked in the future.
  20.             Thread.CurrentThread.Join(100);
  21.             newThread.Interrupt();
  22.             Console.WriteLine("Main thread calls Interrupt on newThread.");
  23.             // Tell newThread to go to sleep.
  24.             //stayAwake.SleepSwitch = true;
  25.             // Wait for newThread to end.
  26.             newThread.Join();
  27.             Console.ReadLine();
  28.   
  29.         }
  30.         
  31.     }
  32.     class StayAwake
  33.     {
  34.         bool sleepSwitch = false;
  35.         public bool SleepSwitch
  36.         {
  37.             set { sleepSwitch = value; }
  38.         }
  39.         public StayAwake() { }
  40.         public void ThreadMethod()
  41.         {
  42.             Console.WriteLine("newThread is executing ThreadMethod.");
  43.             while (!sleepSwitch)
  44.             {
  45.                 try
  46.                 {
  47.                     Thread.Sleep(1000);
  48.                     Console.WriteLine("sleep again");
  49.                 }
  50.                 catch (ThreadInterruptedException)
  51.                 {
  52.                     Console.WriteLine("newThread cannot go to sleep - " + "interrupted by main thread.");
  53.                 }
  54.             }
  55.         }
  56.     }
  57. }

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值