http://www.albahari.com/threading/

给线程传递参数的几种方式:

  1. lambda表达式 ```csharp static void Main() { Thread t = new Thread ( () => Print (“Hello from t!”) ); t.Start(); }

static void Print (string message) { Console.WriteLine (message); }

  1. 2. 在start中给参数,(只能传递一个object)
  2. ```csharp
  3. static void Main()
  4. {
  5. Thread t = new Thread (Print);
  6. t.Start ("Hello from t!");
  7. }
  8. static void Print (object messageObj)
  9. {
  10. string message = (string) messageObj; // We need to cast here
  11. Console.WriteLine (message);
  12. }

防止主线程退出,后台线程以外结束的方法

There are two ways to accomplish this:

  • If you’ve created the thread yourself, call [Join](http://www.albahari.com/threading/#_Join_and_Sleep) on the thread.
  • If you’re on a pooled thread, use an event wait handle.

提升线程优先级

  1. using (Process p = Process.GetCurrentProcess())
  2. p.PriorityClass = ProcessPriorityClass.High;

thread pool (Parallel Task Library)

task

task将thread pool加入线程池

  1. static void Main() // The Task class is in System.Threading.Tasks
  2. {
  3. Task.Factory.StartNew (Go);
  4. }
  5. static void Go()
  6. {
  7. Console.WriteLine ("Hello from the thread pool!");
  8. }

Task.Factory.StartNew returns a Task object, which you can then use to monitor the task — for instance, you can wait for it to complete by calling its [Wait](http://www.albahari.com/threading/part5.aspx#_Waiting_on_Tasks) method.

Any unhandled exceptions are conveniently rethrown onto the host thread when you call a task’s [Wait method](http://www.albahari.com/threading/part5.aspx#_Waiting_on_Tasks). (If you don’t call Wait and instead abandon the task, an unhandled exception will shut down the process as with an ordinary thread.)