我想使用线程优化我的应用程序。我仍然觉得性能不够好,所以我想找到一种优化线程使用的方法。也许ThreadPooling?或重复使用创建的线程?
所以我测试了线程池与创建新线程的关系,结果是肯定的。
结果:
using System;
using System.Threading;
using System.Diagnostics;
namespace ThreadPooling {
class Program {
static void Main(string[] args) {
Actor actor = new Actor();
Stopwatch mywatch = new Stopwatch();
int frame = 0;
long averageTPms = 0;
long averageTms = 0;
while (frame < 500) {
frame += 1;
Console.Clear();
Console.WriteLine("Frame: " + frame);
Console.WriteLine("");
Console.WriteLine("Thread Pool Execution");
mywatch.Restart(); // <- Suggested fix
actor.ProcessWithThreadPoolMethod();
mywatch.Stop();
Console.WriteLine("Time consumed by ProcessWithThreadPoolMethod is : " + mywatch.ElapsedMilliseconds.ToString());
averageTPms += mywatch.ElapsedMilliseconds;
Console.WriteLine("Thread Execution");
mywatch.Restart(); // <- Suggested fix
actor.ProcessWithThreadMethod();
mywatch.Stop();
Console.WriteLine("Time consumed by ProcessWithThreadMethod is : " + mywatch.ElapsedMilliseconds.ToString());
averageTms += mywatch.ElapsedMilliseconds;
Console.WriteLine("");
Console.WriteLine("AverageThreadPooling: " + averageTPms / frame + " ms");
Console.WriteLine("AverageThreadCreation: " + averageTms / frame + " ms");
}
Console.ReadLine();
}
}
class Actor {
private const int threadCount = 8;
private int TPWorkDone = 0;
private int TWorkDone = 0;
public Actor() {
}
public void WaitTPWorkDone() {
while (TPWorkDone < threadCount) {
}
Console.WriteLine("TP WORK DONE");
}
public void ResetTPWorkDone() {
//Console.WriteLine("reseting");
TPWorkDone = 0;
}
public void WaitTWorkDone() {
while (TWorkDone < threadCount) {
}
Console.WriteLine("T WORK DONE");
}
public void ResetTWorkDone() {
//Console.WriteLine("reseting");
TWorkDone = 0;
}
public void ProcessWithThreadPoolMethod() {
for (int i = 0; i < threadCount; i++) {
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolProcess), i);
}
WaitTPWorkDone();
ResetTPWorkDone();
}
public void ProcessWithThreadMethod() {
Thread[] thread = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
thread[i] = new Thread(ThreadProcess);
thread[i].Start(i);
}
WaitTWorkDone();
ResetTWorkDone();
}
public void ThreadPoolProcess(object callback) {
Console.WriteLine("processing: " + (int)callback);
for (int y = 0; y < 512; y++) {
for (int x = 0; x < 512; x++) {
int a = x * x * y * y;
}
}
TPWorkDone += 1;
}
public void ThreadProcess(object callback) {
Console.WriteLine("processing: " + (int)callback);
for (int y = 0; y < 512; y++) {
for (int x = 0; x < 512; x++) {
int a = x * x * y * y;
}
}
TWorkDone += 1;
}
}
}
我希望线程池的性能比创建新线程更好。
编辑:固定时间度量后,线程池似乎表现更好。 感谢J. van Langen