HelloWorld多线程C#应用程序

时间:2012-01-04 02:18:37

标签: c# multithreading

考虑以下来自http://www.albahari.com/threading/的示例:

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”?

3 个答案:

答案 0 :(得分: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 :(得分: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);

    }

}

答案 2 :(得分: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);
  }
}