2015-12-22 35 views
3

主線程和其他線程我驗證了使用單和多線程的執行功能的基準問題。 我在這裏幹嘛?如果是的話,我怎麼能不使用Join()。 如果沒有,建議我。基準在C#

代碼

class Threading1 
{ 
    static void Main (string[] args) 
    { 
    Stopwatch timerMain, timerThreads; 

    // Main thread 
    timerMain = Stopwatch.StartNew(); 
    func1(); 
    func2(); 
    func3(); 
    timerMain.Stop(); 
    Console.WriteLine ("Time taken for Main thread: " + timerMain.ElapsedMilliseconds); 

    // Other threads 
    Thread t1 = new Thread (() => Threading1.func1()); 
    Thread t2 = new Thread (() => Threading1.func2()); 
    Thread t3 = new Thread (() => Threading1.func3()); 
    timerThreads = Stopwatch.StartNew(); 
    t1.Start(); t1.Join(); 
    t2.Start(); t2.Join(); 
    t3.Start(); t3.Join(); 
    timerThreads.Stop(); 
    Console.WriteLine ("Time taken for Other threads: " + timerThreads.ElapsedMilliseconds); 
    } 

    // Find maximum value in an array 
    static void func1() 
    { 
    // Code here. 
    } 

    // Find minimum value in an array 
    static void func2() 
    { 
    // Code here. 
    } 

    // Find average value of an array 
    static void func3() 
    { 
    // Code here. 
    } 
} 

輸出

Time taken for Main thread: 44 
Time taken for other threads: 10 

回答

3

我建議你使用Tasks和方法WaitAll等待,當所有任務都完成。

timerThreads = Stopwatch.StartNew(); 
var t1 = Task.Run(() => Threading1.func1()); 
var t2 = Task.Run(() => Threading1.func2()); 
var t3 = Task.Run(() => Threading1.func3()); 

Task.WaitAll(t1, t2, t3); 
timerThreads.Stop(); 
Console.WriteLine ("Time taken for Other threads: " + timerThreads.ElapsedMilliseconds); 

在你的解決方案中沒有並行工作,所有的線程都是一一執行。

+3

我不建議使用'Task.Factory.StartNew',而使用'Task.Run',這是很容易當你使用'StartNew'無意外得到的東西到UI線程,而不是線程池上運行傳遞調度器時,'Task.Run'總是使用線程池調度器。 –

+0

@ScottChamberlain謝謝你的好評 – Backs

+0

一個快樂的答案,我同意斯科特的優點! +1 – MickyD