2012-01-04 179 views
1

考慮從http://www.albahari.com/threading/採取了以下例子:的HelloWorld多線程C#應用程序

using System; 
using System.Threading; 
class ThreadTest 
{ 
    static void Main() 
    { 
    Thread t = new Thread (WriteY);   // Kick off a new thread 
    t.Start();        // running WriteY() 

    // Simultaneously, do something on the main thread. 
    for (int i = 0; i < 1000; i++) Console.Write ("x"); 
    } 

    static void WriteY() 
    { 
    for (int i = 0; i < 1000; i++) Console.Write ("y"); 
    } 
} 

如何修改代碼以使WriteY()接受一個字符串參數,這樣我可以有一個線程通「x」和一通「y」?

回答

2
using System; 
using System.Threading; 


public class ThreadTest { 

    public static void Main() { 

     Thread t=new Thread(WriteString); 
     t.Start("y"); 
     Thread u=new Thread(WriteString); 
     u.Start("x"); 

     t.Join(); 
     u.Join(); 

    } 

    public static void WriteString (Object o) { 

     for (Int32 i=0;i<1000;++i) Console.Write((String)o); 

    } 

} 
+0

爲什麼您的方法需要JOIN方法,而不是使用Lamba方法? – ChadD 2012-01-04 02:44:47

+0

這不是「需要」,我只是希望在退出「Main」之前確保我的線程已經退出。 – 2012-01-04 02:54:30

+0

@RobertAllanHenniganLeahy我對你的回覆感興趣,只是用它來測試它,但我有一個如下問題 - 我怎麼能通過多個參數?說我想通過循環計數,所以它不固定在1000.謝謝 – harag 2012-01-04 14:24:47

3

嘗試使用lambda表達式:

class ThreadTest 
{ 
    static void Main() 
    { 
    Thread t = new Thread (() => Write("y"));   // Kick off a new thread 
    t.Start();        // running WriteY() 

    // Simultaneously, do something on the main thread. 
    Write("x"); 
    } 

    static void Write(string input) 
    { 
    for (int i = 0; i < 1000; i++) Console.Write (input); 
    } 
} 
1

基本上你需要實現三個轉變。

//1. change how the thread is started 
t.Start("y");        // running WriteY() 

//2.change how the signature of the method 
static void WriteY(object data) 
    { 
    //3. use the data parameter 
    for (int i = 0; i &lt; 1000; i++) Console.Write ((string) data); 
    } 
}