多线程和更改优先级

时间:2018-03-26 08:05:40

标签: c# multithreading

我用3种不同的方法在main中创建3个Threads。

Thread t1 = new Thread(FirstThread);
Thread t2 = new Thread(SecondThread);
Thread t3 = new Thread(ThirdThread);

我需要在每个线程上测量时间并少搜索它们。

用秒表测量时间。我没有找到另一种方式(在c / c ++我知道方法GetThreadTimes)。

static void FirstThread()
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    try
    {
        Enumerable.Range(1, 10000).Select(x => x).Sum();
    }
    finally
    {
        stopwatch.Stop();
        Console.WriteLine(stopwatch.Elapsed);
    }
}

After(on task)动态更改Thread的优先级并再次启动方法示例:

thr2.priority = ThreadPriority.Highest;

我不明白,如果这是 不可能 ,我可以开始更改优先级的线程,因为线程启动1次。

显示正常和低优先级所有线程的显示时间。

P.S。我认为秒表将变量投射比较为双倍,或者我没有看到任何其他方式......

double timeInSecondsPerN = Stopwatch1.Elapsed.TotalMilliseconds

在程序运行时中查看具有不同优先级的线程的工作的主要问题

1 个答案:

答案 0 :(得分:1)

线程优先级不一定能使任务更快或完成更多的工作' 如果将3个线程设置为优先级最高 - 那么它们将以相同的速度/速率竞争CPU周期,可能与它们都是线程优先级低于正常的速度相同。

所有这一切意味着如果你的应用程序陷入僵局并争夺CPU周期,它就知道首先要满足哪个线程。

如果将所有线程设置为相同的高值,.Net的此功能将失去其优势。如果您对应用程序中所有其他线程之前真正需要满足的线程使用更高优先级设置,则该功能仅具有值。

例如:IO使用率低的重要计算任务。 (加密,加密货币,哈希等)

如果您的应用程序没有达到线程锁定或使用100%的cpu核心,那么优先级功能将永远不会启动。

Thread.Priority上的Microsoft网站很好地证明了优先级的效果。

https://msdn.microsoft.com/en-us/library/system.threading.thread.priority(v=vs.110).aspx

using System;
using System.Threading;
using Timers = System.Timers;

class Test
{
    static void Main()
    {
        PriorityTest priorityTest = new PriorityTest();

        Thread thread1 = new Thread(priorityTest.ThreadMethod);
        thread1.Name = "ThreadOne";
        Thread thread2 = new Thread(priorityTest.ThreadMethod);
        thread2.Name = "ThreadTwo";
        thread2.Priority = ThreadPriority.BelowNormal;
        Thread thread3 = new Thread(priorityTest.ThreadMethod);
        thread3.Name = "ThreadThree";
        thread3.Priority = ThreadPriority.AboveNormal;

        thread1.Start();
        thread2.Start();
        thread3.Start();
        // Allow counting for 10 seconds.
        Thread.Sleep(10000);
        priorityTest.LoopSwitch = false;
    }
}

class PriorityTest
{
    static bool loopSwitch;
    [ThreadStatic] static long threadCount = 0;

    public PriorityTest()
    {
        loopSwitch = true;
    }

    public bool LoopSwitch
    {
        set{ loopSwitch = value; }
    }

    public void ThreadMethod()
    {
        while(loopSwitch)
        {
            threadCount++;
        }
        Console.WriteLine("{0,-11} with {1,11} priority " +
            "has a count = {2,13}", Thread.CurrentThread.Name, 
            Thread.CurrentThread.Priority.ToString(), 
            threadCount.ToString("N0")); 
    }
}
// The example displays output like the following:
//    ThreadOne   with      Normal priority has a count =   755,897,581
//    ThreadThree with AboveNormal priority has a count =   778,099,094
//    ThreadTwo   with BelowNormal priority has a count =     7,840,984