Loading

C# Thread2——线程优先级

C#中Thread的优先级不是决定每个线程被执行顺序。它决定了线程可以占用CPU的时间

Thread的优先级设置是自带的枚举类型"ThreadPriority"

 

 [ComVisible(true)]
    public enum ThreadPriority
    {
        //
        // 摘要:
        //     System.Threading.Thread 可以安排在具有任何其他优先级的线程之后。
        Lowest = 0,
        //
        // 摘要:
        //     System.Threading.Thread 可以安排在使用的线程之后 Normal 优先级之前 Lowest 优先级。
        BelowNormal = 1,
        //
        // 摘要:
        //     System.Threading.Thread 可以安排在使用的线程之后 AboveNormal 优先级之前 BelowNormal 优先级。 线程所具有的
        //     Normal 默认优先级。
        Normal = 2,
        //
        // 摘要:
        //     System.Threading.Thread 可以安排在使用的线程之后 Highest 优先级之前 Normal 优先级。
        AboveNormal = 3,
        //
        // 摘要:
        //     System.Threading.Thread 可以安排在具有任何其他优先级的线程之前。
        Highest = 4
    }

 

看下面两个线程的例子

class Program
    {
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(PrintCount);
            Thread thread2 = new Thread(PrintCount);
            thread1.Priority = ThreadPriority.Highest;
            thread2.Priority = ThreadPriority.Lowest;
            thread1.Start();
            thread2.Start();
            Thread.Sleep(2000);
            thread1.Abort();
            thread2.Abort();
            Console.Read();
        }
        private static void  PrintCount()
        {
            int flag = 0;
            while (true)
            {
                Console.WriteLine($"{Thread.CurrentThread.Name}priority{Thread.CurrentThread.Priority}count:{flag++ }");
            }
        }
    }

我们运行了两个子线程,第一个线程设置为了最高级,第二个则是最低级,在两秒内,我们看看下面的结果

 

 第一个设置为高级的线程在两秒内运行了912次,而设置为低级的则运行了645次

因为我们计算机性能都比较好了,基本都是几核的。接下来我们稍微修改下代码,我们将所有的线程都放知道我们系统的第一个CPU上运行

来看看运行状况。

class Program
    {
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(PrintCount);
            Thread thread2 = new Thread(PrintCount);
            thread1.Priority = ThreadPriority.Highest;
            thread2.Priority = ThreadPriority.Lowest;
            thread1.Start();
            thread2.Start();
            Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);//设置到第一个cup上运行
            Thread.Sleep(2000);
            thread1.Abort();
            thread2.Abort();
            Console.Read();
        }
        private static void  PrintCount()
        {
            int flag = 0;
            while (true)
            {
                Console.WriteLine($"{Thread.CurrentThread.Name}priority{Thread.CurrentThread.Priority}count:{flag++ }");
            }
        }

我们看看两秒内两个线程的运行情况

 

 由此可见,低等级的次数更少了,这是由于只使用了一个CPU核心,所以它大多时间都是在处理高等级的线程,更少的时间处理低等级。这里可以看到差距更加的明显了。

 

 

 

posted @ 2019-11-26 01:16  BruceNeter  阅读(831)  评论(0编辑  收藏  举报