2012-09-12 57 views
0

我有一個數組中的多個任務,用於計算給定範圍內的素數。要進行任務與線程性能的比較,我想在任務中使用線程,然後檢查性能統計信息。將線程分配給C#中的任務

如何將線程與任務中使用,到目前爲止,這是我做了什麼:

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; 
    } 
+1

「任務內的線程」或「線程而不是任務」?第一個似乎不合邏輯。 –

+0

我不想用線程替換任務..我想在線程的幫助下完成任務。 – faizanjehangir

+1

您從根本上誤解了任務如何工作。這在SO文章中無法解決,它不能解決「如果你能想象整本書能夠回答你的問題,你就會問太多」FAQ條目。你需要教育自己,有很多好書和教程可用。 –

回答

1

任務的要點是「simplifying the process of adding parallelism and concurrency to applications」。事實上,(從http://msdn.microsoft.com/en-us/library/dd537609):

在後臺,任務排隊到線程池,這一直是 與算法(如爬山)決定和 調整,最大限度地提高吞吐量的線程數增加。這使得 任務相對輕量級,並且您可以創建其中的許多任務來啓用細粒度並行。爲了補充這一點,採用廣爲人知的工作竊取算法來提供負載平衡。

總而言之,任務在沒有太多麻煩和糾結的情況下完成線程工作。

要比較兩者,請考慮使用Parrallel.ForEach來完成任務。例如:

public class PrimeRange 
{ 
    public int Start; 
    public int Snd; 
} 

List<PrimeRange> primes = new [] 
{ 
    new PrimeRange{Start = 0, End = 1000}, 
    new PrimeRange{Start = 1001, End = 2000} 
    // An so on 
}; 
Parallel.ForEach(primes, x => CalculatePrimes(x, OnResult()))); 

其中CalculatePrimes是採用一個PrimeRange和委託時的素數已被計算來調用的方法。 Parraler.ForEach將爲素數的每個元素啓動一個任務,並在其上運行CalculatePrimes()併爲您處理線程分配和調度。

比較它的線程,使用類似:

List<Thread> threads = new List<Thread>(); 
foreach(PrimeRange primeRange in primes) 
{ 
    threads = new Thread(CalculatePrimes).Start(x); 
} 
foreach(var thread in threads) 
{ 
    thread.Join(); 
}  

其中CalculatePrimes需要也存儲結果(或類似的東西)。有關在運行線程上等待的更多信息,請參閱C# Waiting for multiple threads to finish

您可以使用StopWatch來計算結果。

+0

_進行任務與線程性能的比較_ –

+0

@HenkHolterman即將到來。我只想先獲得一些基本信息。 – akton

+0

好的,所以爲了繼續比較,我是否需要使用像你所建議的那樣的任務的並行執行,還是我必須明確地分配線程? – faizanjehangir

相關問題