• C#多线程学习


    任何程序在执行时,至少有一个主线程。在.net framework class library中,所有与多线程机制应用相关的类都是放在System.Threading命名空间中的。如果你想在你的应用程序中使用多线程,就必须包含这个类。

    Thread类有几个至关重要的方法,描述如下:

    Start():启动线程;

    Sleep(int):静态方法,暂停当前线程指定的毫秒数;

    Abort():通常使用该方法来终止一个线程;

    Suspend():该方法并不终止未完成的线程,它仅仅挂起线程,以后还可恢复;

    Resume():恢复被Suspend()方法挂起的线程的执行。

     

    一个直观印象的线程示例:

    using System;
    using System.Threading;

    namespace ThreadTest
    {
      
    class RunIt
      {
        [STAThread]
        
    static void Main(string[] args)
        {
          Thread.CurrentThread.Name
    ="System Thread";//给当前线程起名为"System Thread"
    Console.WriteLine(Thread.CurrentThread.Name+"'Status:"+Thread.CurrentThread.ThreadState);
          Console.ReadLine();
        }
      }
    }

    输出如下:

    System Thread's Status:Running

     

    在C#中,线程入口是通过ThreadStart代理(delegate)来提供的,你可以把ThreadStart理解为一个函数指针,指向线程要执行的函数,当调用Thread.Start()方法后,线程就开始执行ThreadStart所代表或者说指向的函数。

    1.所有线程都是依附于Main()函数所在的线程的,Main()函数是C#程序的入口,起始线程可以称之为主线程。如果所有的前台线程都停止了,那么主线程可以终止,而所有的后台线程都将无条件终止。所有的线程虽然在微观上是串行执行的,但是在宏观上你完全可以认为它们在并行执行。

     

    2.ThreadState 属性的取值如下,这个属性代表了线程运行时状态,在不同的情况下有不同的值,我们有时候可以通过对该值的判断来设计程序流程。:

    Aborted:线程已停止;

    AbortRequested:线程的Thread.Abort()方法已被调用,但是线程还未停止;

    Background:线程在后台执行,与属性Thread.IsBackground有关;

    Running:线程正在正常运行;

    Stopped:线程已经被停止;

    StopRequested:线程正在被要求停止;

    Suspended:线程已经被挂起(此状态下,可以通过调用Resume()方法重新运行);

    SuspendRequested:线程正在要求被挂起,但是未来得及响应;

    Unstarted:未调用Thread.Start()开始线程的运行;

    WaitSleepJoin:线程因为调用了Wait(),Sleep()或Join()等方法处于封锁状态;

     

    3.当线程之间争夺CPU时间时,CPU 是按照线程的优先级给予服务的。在C#应用程序中,用户可以设定5个不同的优先级,由高到低分别是Highest,AboveNormal,Normal,BelowNormal,Lowest,在创建线程时如果不指定优先级,那么系统默认为ThreadPriority.Normal。

    例:

    using System;
    using System.Threading;

    namespace ThreadTest
    {
    public class Alpha
    {
    public void Beta()
    {
    while (true)
    {
    Console.WriteLine(
    "Alpha.Beta is running in its own thread.");
    }
    }
    };

    public class Simple
    {
    public static int Main()
    {
      Console.WriteLine(
    "Thread Start/Stop/Join Sample");
    Alpha oAlpha
    = new Alpha();
       file:
    //这里创建一个线程,使之执行Alpha类的Beta()方法
       Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
       oThread.Start();
      
    while (!oThread.IsAlive)
       Thread.Sleep(
    1);
       oThread.Abort();
       oThread.Join();
       Console.WriteLine();
       Console.WriteLine(
    "Alpha.Beta has finished");
      
    try
       {
         Console.WriteLine(
    "Try to restart the Alpha.Beta thread");
         oThread.Start();
       }
      
    catch (ThreadStateException)
       {
         Console.Write(
    "ThreadStateException trying to restart Alpha.Beta. ");
         Console.WriteLine(
    "Expected since aborted threads cannot be restarted.");
         Console.ReadLine();
       }
      
    return 0;
       }
    }
    }

     

    C#提供了一个关键字lock,它可以把一段代码定义为互斥段(critical section),互斥段在一个时刻内只允许一个线程进入执行,而其他线程必须等待。在C#中,关键字lock定义如下:

    lock(expression) statement_block

    expression代表你希望跟踪的对象,通常是对象引用。

    • 如果你想保护一个类的实例,一般地,你可以使用this;
    • 如果你想保护一个静态变量(如互斥代码段在一个静态方法内部),一般使用类名就可以了。

    而statement_block就是互斥段的代码,这段代码在一个时刻内只可能被一个线程执行。

    示例如下:

    using System;
    using System.Threading;

    namespace ThreadSimple
    {
       
    internal class Account
        {
           
    int balance;
            Random r
    = new Random();
           
           
    internal Account(int initial)
            {
                balance
    = initial;
            }
           
    internal int Withdraw(int amount)
            {
               
    if (balance < 0)
                {
                   
    //如果balance小于0则抛出异常
                    throw new Exception("Negative Balance");
                }
               
    //下面的代码保证在当前线程修改balance的值完成之前
               
    //不会有其他线程也执行这段代码来修改balance的值
               
    //因此,balance的值是不可能小于0 的
                lock (this)
                {
                    Console.WriteLine(
    "Current Thread:"+Thread.CurrentThread.Name);
                   
    //如果没有lock关键字的保护,那么可能在执行完if的条件判断之后
                   
    //另外一个线程却执行了balance=balance-amount修改了balance的值
                   
    //而这个修改对这个线程是不可见的,所以可能导致这时if的条件已经不成立了
                   
    //但是,这个线程却继续执行balance=balance-amount,所以导致balance可能小于0
                    if (balance >= amount)
                    {
                        Thread.Sleep(
    5);
                        balance
    = balance - amount;
                       
    return amount;
                    }
                   
    else
                    {
                       
    return 0; // transaction rejected
                      }
                }
            }
           
    internal void DoTransactions()
            {
               
    for (int i = 0; i < 100; i++)
                Withdraw(r.Next(
    -50, 100));
            }
        }
       
    internal class Test
        {
           
    static internal Thread[] threads = new Thread[10];
           
    public static void Main()
            {
                Account acc
    = new Account (0);
               
    for (int i = 0; i < 10; i++)
                {
                    Thread t
    = new Thread(new ThreadStart(acc.DoTransactions));
                    threads[i]
    = t;
                }
               
    for (int i = 0; i < 10; i++)
                    threads[i].Name
    =i.ToString();
               
    for (int i = 0; i < 10; i++)
                    threads[i].Start();
                Console.ReadLine();
            }
        }
    }

     

    当多线程公用一个对象时,也会出现和公用代码类似的问题,这种问题就不应该使用lock关键字了,这里需要用到System.Threading中的一个类Monitor,我们可以称之为监视器,Monitor提供了使线程共享资源的方案。

    Monitor类可以锁定一个对象,一个线程只有得到这把锁才可以对该对象进行操作。对象锁机制保证了在可能引起混乱的情况下一个时刻只有一个线程可以访问这个对象。 Monitor必须和一个具体的对象相关联,但是由于它是一个静态的类,所以不能使用它来定义对象,而且它的所有方法都是静态的,不能使用对象来引用。下面代码说明了使用Monitor锁定一个对象的情形:

    ......

    Queue oQueue=new Queue();

    ......

    Monitor.Enter(oQueue);

    ......//现在oQueue对象只能被当前线程操纵了

    Monitor.Exit(oQueue);//释放锁

     

    在多线程的程序中,经常会出现两种情况:

    一种情况: 应用程序中,线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应

    这一般使用ThreadPool(线程池)来解决;

    另一种情况:线程平时都处于休眠状态,只是周期性地被唤醒

    这一般使用Timer(定时器)来解决;

    ThreadPool类提供一个由系统维护的线程池(可以看作一个线程的容器),

    将线程安放在线程池里,需使用ThreadPool.QueueUserWorkItem()方法,该方法的原型如下:

    //将一个线程放进线程池,该线程的Start()方法将调用WaitCallback代理对象代表的函数

    public static bool QueueUserWorkItem(WaitCallback);

    //重载的方法如下,参数object将传递给WaitCallback所代表的方法

    public static bool QueueUserWorkItem(WaitCallback, object);

    在这里你无需自己建立线程,只需把你要做的工作写成函数,然后作为参数传递给ThreadPool.QueueUserWorkItem()方法就行了,传递的方法就是依靠WaitCallback代理对象,而线程的建立、管理、运行等工作都是由系统自动完成的,你无须考虑那些复杂的细节问题。

    首先程序创建了一个ManualResetEvent对象,该对象就像一个信号灯,可以利用它的信号来通知其它线程。

    在初始化以后,该对象将保持原来的状态不变,直到它的Reset()或者Set()方法被调用:

    Reset()方法:将其设置为无信号状态;

    Set()方法:将其设置为有信号状态。

    WaitOne()方法:使当前线程挂起,直到ManualResetEvent对象处于有信号状态,此时该线程将被激活.然后,程序将向线程池中添加工作项,这些以函数形式提供的工作项被系统用来初始化自动建立的线程。当所有的线程都运行完了以后,ManualResetEvent.Set()方法被调用,因为调用了ManualResetEvent.WaitOne()方法而处在等待状态的主线程将接收到这个信号,于是它接着往下执行,完成后边的工作。

    using System;
    using System.Collections;
    using System.Threading;

    namespace ThreadExample
    {
       
    //这是用来保存信息的数据结构,将作为参数被传递
        public class SomeState
        {
         
    public int Cookie;
         
    public SomeState(int iCookie)
          {
            Cookie
    = iCookie;
          }
        }

       
    public class Alpha
        {
      
    public Hashtable HashCount;
      
    public ManualResetEvent eventX;
      
    public static int iCount = 0;
      
    public static int iMaxCount = 0;
      
           
    public Alpha(int MaxCount)
      {
             HashCount
    = new Hashtable(MaxCount);
             iMaxCount
    = MaxCount;
      }

      
    //线程池里的线程将调用Beta()方法
      public void Beta(Object state)
      {
         
    //输出当前线程的hash编码值和Cookie的值
             Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(),((SomeState)state).Cookie);
          Console.WriteLine(
    "HashCount.Count=={0}, Thread.CurrentThread.GetHashCode()=={1}", HashCount.Count, Thread.CurrentThread.GetHashCode());
         
    lock (HashCount)
          {
           
    //如果当前的Hash表中没有当前线程的Hash值,则添加之
            if (!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode()))
                 HashCount.Add (Thread.CurrentThread.GetHashCode(),
    0);
             HashCount[Thread.CurrentThread.GetHashCode()]
    =
                ((
    int)HashCount[Thread.CurrentThread.GetHashCode()])+1;
          }
             
    int iX = 2000;
              Thread.Sleep(iX);
             
    //Interlocked.Increment()操作是一个原子操作,具体请看下面说明
              Interlocked.Increment(ref iCount);

             
    if (iCount == iMaxCount)
              {
              Console.WriteLine();
            Console.WriteLine(
    "Setting eventX ");
            eventX.Set();
            }
        }
      }

           
    public class SimplePool
            {
               
    public static int Main(string[] args)
                {
                    Console.WriteLine(
    "Thread Pool Sample:");
                   
    bool W2K = false;
                   
    int MaxCount = 10;//允许线程池中运行最多10个线程
                   
    //新建ManualResetEvent对象并且初始化为无信号状态
                    ManualResetEvent eventX = new ManualResetEvent(false);
                    Console.WriteLine(
    "Queuing {0} items to Thread Pool", MaxCount);
                    Alpha oAlpha
    = new Alpha(MaxCount);
                   
    //创建工作项
                   
    //注意初始化oAlpha对象的eventX属性
                    oAlpha.eventX = eventX;
                    Console.WriteLine(
    "Queue to Thread Pool 0");
                   
    try
                    {
                       
    //将工作项装入线程池
                       
    //这里要用到Windows 2000以上版本才有的API,所以可能出现NotSupportException异常
                        ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta), new SomeState(0));
                        W2K
    = true;
                    }
                   
    catch (NotSupportedException)
                    {
                        Console.WriteLine(
    "These API's may fail when called on a non-Windows 2000 system.");
                        W2K
    = false;
                    }
                   
    if (W2K)//如果当前系统支持ThreadPool的方法.
                    {
                       
    for (int iItem=1;iItem < MaxCount;iItem++)
                        {
                           
    //插入队列元素
                            Console.WriteLine("Queue to Thread Pool {0}", iItem);
                            ThreadPool.QueueUserWorkItem(
    new WaitCallback(oAlpha.Beta), new SomeState(iItem));
                        }
                        Console.WriteLine(
    "Waiting for Thread Pool to drain");
                       
    //等待事件的完成,即线程调用ManualResetEvent.Set()方法
                        eventX.WaitOne(Timeout.Infinite,true);
                       
    //WaitOne()方法使调用它的线程等待直到eventX.Set()方法被调用
                        Console.WriteLine("Thread Pool has been drained (Event fired)");
                        Console.WriteLine();
                        Console.WriteLine(
    "Load across threads");
                       
    foreach(object o in oAlpha.HashCount.Keys)
                            Console.WriteLine(
    "{0} {1}", o, oAlpha.HashCount[o]);
                    }
                    Console.ReadLine();
                   
    return 0;
                }
            }
        }
    }

     

    Timer类:设置一个定时器,定时执行用户指定的函数。

    定时器启动后,系统将自动建立一个新的线程,执行用户指定的函数。

    初始化一个Timer对象:

    Timer timer = new Timer(timerDelegate, s,1000, 1000);

    // 第一个参数:指定了TimerCallback 委托,表示要执行的方法;

    // 第二个参数:一个包含回调方法要使用的信息的对象,或者为空引用;

    // 第三个参数:延迟时间——计时开始的时刻距现在的时间,单位是毫秒,指定为“0”表示立即启动计时器;

    // 第四个参数:定时器的时间间隔——计时开始以后,每隔这么长的一段时间,TimerCallback所代表的方法将被调用一次,单位也是毫秒。指定 Timeout.Infinite 可以禁用定期终止。

    Timer.Change()方法:修改定时器的设置。(这是一个参数类型重载的方法)

    使用示例: timer.Change(1000,2000);

    如何控制好多个线程相互之间的联系,不产生冲突和重复,这需要用到互斥对象,即:System.Threading 命名空间中的 Mutex 类。线程使用Mutex.WaitOne()方法等待Mutex对象被释放,如果它等待的Mutex对象被释放了,它就自动拥有这个对象,直到它调用Mutex.ReleaseMutex()方法释放这个对象,而在此期间,其他想要获取这个Mutex对象的线程都只有等待。

    其中还用到AutoResetEvent类的对象,可以把它理解为一个信号灯。这里用它的有信号状态来表示一个线程的结束。

    // AutoResetEvent.Set()方法设置它为有信号状态

    // AutoResetEvent.Reset()方法设置它为无信号状态

    using System;
    using System.Threading;

    namespace ThreadExample
    {
       
    public class MutexSample
        {
         
    static Mutex gM1;
         
    static Mutex gM2;
         
    const int ITERS = 100;
         
    static AutoResetEvent Event1 = new AutoResetEvent(false);
         
    static AutoResetEvent Event2 = new AutoResetEvent(false);
         
    static AutoResetEvent Event3 = new AutoResetEvent(false);
         
    static AutoResetEvent Event4 = new AutoResetEvent(false);

         
    public static void Main(String[] args)
          {
                Console.WriteLine(
    "Mutex Sample ");
               
    //创建一个Mutex对象,并且命名为MyMutex
                gM1 = new Mutex(true,"MyMutex");
               
    //创建一个未命名的Mutex 对象.
                gM2 = new Mutex(true);
                Console.WriteLine(
    " - Main Owns gM1 and gM2");

                AutoResetEvent[] evs
    = new AutoResetEvent[4];
                evs[
    0] = Event1; //为后面的线程t1,t2,t3,t4定义AutoResetEvent对象
                evs[1] = Event2;
                evs[
    2] = Event3;
                evs[
    3] = Event4;

                MutexSample tm
    = new MutexSample( );
                Thread t1
    = new Thread(new ThreadStart(tm.t1Start));
                Thread t2
    = new Thread(new ThreadStart(tm.t2Start));
                Thread t3
    = new Thread(new ThreadStart(tm.t3Start));
                Thread t4
    = new Thread(new ThreadStart(tm.t4Start));
                t1.Start( );
    // 使用Mutex.WaitAll()方法等待一个Mutex数组中的对象全部被释放
                t2.Start( );// 使用Mutex.WaitOne()方法等待gM1的释放
                t3.Start( );// 使用Mutex.WaitAny()方法等待一个Mutex数组中任意一个对象被释放
                t4.Start( );// 使用Mutex.WaitOne()方法等待gM2的释放

                Thread.Sleep(
    2000);
                Console.WriteLine(
    " - Main releases gM1");
                gM1.ReleaseMutex( );
    //线程t2,t3结束条件满足

                Thread.Sleep(
    1000);
                Console.WriteLine(
    " - Main releases gM2");
                gM2.ReleaseMutex( );
    //线程t1,t4结束条件满足

               
    //等待所有四个线程结束
                WaitHandle.WaitAll(evs);
                Console.WriteLine(
    " Mutex Sample");
                Console.ReadLine();
          }

         
    public void t1Start( )
          {
                Console.WriteLine(
    "t1Start started, Mutex.WaitAll(Mutex[])");
                Mutex[] gMs
    = new Mutex[2];
                gMs[
    0] = gM1;//创建一个Mutex数组作为Mutex.WaitAll()方法的参数
                gMs[1] = gM2;
                Mutex.WaitAll(gMs);
    //等待gM1和gM2都被释放
                Thread.Sleep(2000);
                Console.WriteLine(
    "t1Start finished, Mutex.WaitAll(Mutex[]) satisfied");
                Event1.Set( );
    //线程结束,将Event1设置为有信号状态
          }
         
    public void t2Start( )
          {
                Console.WriteLine(
    "t2Start started, gM1.WaitOne( )");
                gM1.WaitOne( );
    //等待gM1的释放
                Console.WriteLine("t2Start finished, gM1.WaitOne( ) satisfied");
                Event2.Set( );
    //线程结束,将Event2设置为有信号状态
          }
         
    public void t3Start( )
          {
                Console.WriteLine(
    "t3Start started, Mutex.WaitAny(Mutex[])");
                Mutex[] gMs
    = new Mutex[2];
                gMs[
    0] = gM1;//创建一个Mutex数组作为Mutex.WaitAny()方法的参数
                gMs[1] = gM2;
                Mutex.WaitAny(gMs);
    //等待数组中任意一个Mutex对象被释放
                Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])");
                Event3.Set( );
    //线程结束,将Event3设置为有信号状态
          }
         
    public void t4Start( )
          {
                Console.WriteLine(
    "t4Start started, gM2.WaitOne( )");
                gM2.WaitOne( );
    //等待gM2被释放
                Console.WriteLine("t4Start finished, gM2.WaitOne( )");
                Event4.Set( );
    //线程结束,将Event4设置为有信号状态
          }
        }
    }

     

    摘自:http://www.cnblogs.com/xugang/archive/2008/04/06/1138856.html

  • 相关阅读:
    UG二次开发-CAM-获取修改路径参数
    多线程01
    MFC的对话框使用Scintilla
    CATIA的后处理
    win32窗体中使用Scintilla窗体
    string的reserve和resize
    前端宝典
    MarkDown学习
    JAVA中构造方法总结
    IDEA中maven和tomcat的配置
  • 原文地址:https://www.cnblogs.com/mane/p/1835283.html
Copyright © 2020-2023  润新知