2009-09-23 122 views
0

我正在學習線程。我正在使用線程來處理整數和字符串的數組。C# - 處理線程幫助

實施例:

class Program 
{ 
    static void Main() 
    { 
    ArrayProcess pr=new ArrayProcess(); 
    ThreadStart callback1 = new ThreadStart(pr.PrintNumbers); 
    ThreadStart callback2 = new ThreadStart(pr.PrintStrings); 
    callback1 += callback2; 
    Thread secondaryThread = new Thread(callback1); 
    secondaryThread.Name = "worker1"; 
    secondaryThread.Start(); 
    Console.ReadKey(true); 
    } 
} 


class ArrayProcess 
{ 
public void PrintNumbers() 
{ 
    int[] a = new int[] { 10, 20, 30, 40, 50 }; 
    foreach (int i in a) 
    { 
     Console.WriteLine(i); 
     Thread.Sleep(1000); 
     Console.WriteLine("Printing Numbers"); 
    } 

} 


public void PrintStrings() 
{ 
    string[] str = new string[] { "one", "two", "three", "four", "five" }; 
    foreach (string st in str) 
    { 
     Console.WriteLine(st); 
     Thread.Sleep(1000); 
     Console.WriteLine("Printing string"); 
    } 
} 

} 


根據該碼陣列的執行是同步的(即)int數組進行處理,然後再字符串array.Now我怎樣才能重新設計代碼來實現異步執行
(IE)10,20,一,30,二,三,......

回答

3

您是實際只能創建一個額外的線程。嘗試使用此方法得到兩個,異步線程:

ThreadStart callback1 = new ThreadStart(pr.PrintNumbers); 
ThreadStart callback2 = new ThreadStart(pr.PrintStrings); 

Thread t1 = new Thread(callback1); 
Thread t2 = new Thread(callback2); 
t1.Name = "worker1"; 
t1.Start(); 
t2.Name = "worker2"; 
t2.Start(); 

一旦你掌握了線程的基礎知識,我建議你看看BackgroundWorker作爲管理線程更簡單的方法。

+0

感謝Eric的建議和鏈接 – user160677 2009-09-23 23:11:43