i用3种不同的方法创建3个线程。
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);
}
}
(在任务上(动态更改线程的优先级,然后再次启动方法示例:
thr2.priority = ThreadPriority.Highest;
我不明白,因为如果这是不可能的,我可以开始使用重点变化的线程,因为线程启动了1次。
以正常和低优先级显示在显示时间。
P.S。我认为秒表将变量铸件比较两倍,或者我看不到任何其他方法...
double timeInSecondsPerN = Stopwatch1.Elapsed.TotalMilliseconds
在程序运行时
线程优先级不一定会更快地完成任务或完成'更多工作'如果将3个线程设置为优先级最高 - 那么他们都将以相同的速度/速率争夺CPU周期,可能与它们都是线程优先级相同的速度。
。这意味着,如果您的申请陷入僵局并争夺CPU周期,它将知道首先要满足的线程。
如果将所有线程设置为相同的高值,则.NET的此功能将失去其好处。该功能仅具有值,如果您使用较高的优先级设置来实现真正需要在应用程序中所有其他方面满足的线程。
eg:使用较低IO的重要计算任务。(加密,加密货币,哈希等(
如果您的应用程序未达到螺纹锁定或利用CPU核心的100%,则优先级功能将永远不会启动。
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