我在一个数组中有多个任务,用于计算给定范围内的素数。为了比较任务与线程性能,我想在任务中使用线程,然后检查性能统计信息。
线程将如何用于任务,到目前为止,这就是我所做的:
public Form1()
{
InitializeComponent();
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
this.scheduler = TaskScheduler.FromCurrentSynchronizationContext();
this.numericUpDown1.Maximum = int.MaxValue;
}
private void btnCalculate_Click(object sender, EventArgs e)
{
//get the lower and upper bounds for prime range
int lower = int.Parse(this.numericUpDown1.Value.ToString());
int upper = 0 ;
//get the time in milliseconds for task deadline
int taskDeadline = int.Parse(this.time.Text);
//determine tasks completed
int tasksCompleted = 0;
Random random = new Random();
for (int taskCount = 1; taskCount <= 1; ++taskCount)
{
int taskArraySize = taskCount * 100;
Task[] taskArray = new Task[taskArraySize];
this.txtNumOfPrimes.Text += "Performing test for " +
taskArraySize.ToString() +
" tasks" +
Environment.NewLine +
Environment.NewLine;
for (int i = 0; i < taskArray.Length; i++)
{
upper = random.Next(5, 10);
taskArray[i] = new Task(() => getPrimesInRange(lower, upper));
taskArray[i].Start();
bool timeout = taskArray[i].Wait(taskDeadline);
if (!timeout)
{
// If it hasn't finished at timeout display message
this.txtNumOfPrimes.Text +=
"Message to User: Task not completed, Status=> " +
taskArray[i].Status.ToString() +
Environment.NewLine;
}
else
{
this.txtNumOfPrimes.Text += "Task completed in timeout " +
", CPU usage: " + this.getCurrentCpuUsage() +
", RAM usage: " +
this.getAvailableRAM() +
Environment.NewLine;
tasksCompleted++;
}
}
}
this.txtNumOfPrimes.Text += Environment.NewLine;
this.txtNumOfPrimes.Text +=
"Tasks Completed: " +
tasksCompleted.ToString() +
Environment.NewLine;
}